1. The background

Let’s start learning MyBatis.

2. What is MyBatis?

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping.

MyBatis eliminates almost all of the JDBC code and the work of setting parameters and fetching result sets. MyBatis can configure and map primitive types, interfaces, and Java POJOs (Plain Old Java Objects) to records in the database via simple XML or annotations.

MyBatis focuses on mapping interface methods to XML.

3. Quick examples

Get to know MyBatis first with an example of integrating MyBatis in a project. Step 1: Create a Maven project Create a Maven project and modify the POM file to import Mybatis.

<dependency> <groupId>org.mybatis</groupId> <artifactId> <version>3.3.1</version> </dependency>Copy the code

Step 2: Configure MyBatis. First create a folder mapper under the resouces folder and add a new file MyBatis -config. XML to this folder.

<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE configuration PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" Value = "JDBC: mysql: / / 192.168.1.111:3306 / mybatisdemo? UseSSL = false" / > < property name = "username" value = "root" / > < property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/CountryMapper.xml"/> </mappers> </configuration>Copy the code
  • This is the main mybatis configuration file that specifies the transaction type to be JDBC, data source
  • Driver Configures the JDBC driver of mysql
  • The URL is the connection string
  • Username and password are the database connection account and password

With the above two steps, we have configured the project library dependency, the data source. Let’s start with an example query.

Step 3: Create a database. Here you need a country table. See the example at the end of this article for the complete table construction.

Step 4: Build an entity bean

public class Country {
    public Long id;
    public String countryName;
    public String countryCode;
}

Copy the code

Step 5: Establish a connection, query the database and obtain an object

public class MainClass {

    public static void main(String[] args) throws IOException {
        System.out.println("ready...");

        String resource = "mapper/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        try (SqlSession session = sqlSessionFactory.openSession()) {
            Country blog = (Country) session.selectOne("cn.zyfvir.CountryMapper.selectBlog", 1);
            printf(blog);
        }
    }

    private static void printf(Country blog) {
        System.out.println("" + blog.id + ", " + blog.countryName);
    }
}
Copy the code
  • “Mapper /mybatis-config.xml”; Configuration file and passed to SqlSessionFactoryBuilder as an InputStream parameter InputStream object.
  • SqlSessionFactoryBuilder Builds an SqlSessionFactory SQL session factory object from this configuration file.
  • After the SQL session factory object is opened, an SqlSession session is established to indicate that the database connection is complete.
  • A data connection can query, execute the session. The selectOne (” cn. Zyfvir. CountryMapper. SelectBlog “, 1); An object is queried and the serial number automatically becomes a Countr object
  • Finally, close the session and release the resources.

4. Some discussion

Mybatis supports both XML and annotations. For example, in addition to writing XML configuration mybatis above, you can also directly use Java code to configure, for example:

DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
Copy the code

Of course, it is also possible to write query mappings using Java annotations without relying on XML.

package org.mybatis.example;
public interface BlogMapper {
  @Select("SELECT * FROM blog WHERE id = #{id}")
  Blog selectBlog(int id);
}
Copy the code

So the question is: XML or annotations for mapping?

  • Using annotations to map simple statements makes the code more concise
  • But for slightly more complex statements, Java annotations are not only inadequate, they can also clutter up your already complex SQL statements.
  • Therefore, if you need to do something complicated, it is best to map statements in XML.
  • Tip: It’s up to you and your team how you choose to configure the mapping and whether you think you should unify the mapping statement definition.

In other words, never stick to one approach; you can easily migrate and switch between annotation-based and XML-based statement mapping.

5. Extension

It is recommended that the interface call be used instead of the string full name call in the previous call example:

Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
Copy the code

This is similar to how Java objects are called with fully qualified names. In this way, the name can be mapped directly to the mapper class with the same name in the namespace, and the mapped SELECT statement can be matched to a method with the corresponding name, parameter, and return type.

Create a Mapper interface class:

public interface CountryMapper {
    Country selectBlog(int id);
}

Copy the code

And then call it this way

CountryMapper mapper = session.getMapper(CountryMapper.class);
Country blog = mapper.selectBlog(1);
Copy the code

The second approach has many advantages:

  • It doesn’t rely on string literals, so it’s a bit safer to avoid errors;
  • IDEA has code completion function, which can help you select quickly.
  • More concise, easier to read.
  • Therefore, the second method is recommended

A try-with-resources statement can automatically release resources. A try-with resource statement is a statement that declares one or more resource declarations. A resource is an object of the program with which it must be closed after completion. The try-with resource statement ensures that each resource is closed at the end of the statement. Any implemented object, java.lang.AutoCloseable including all implemented objects java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from a file. BufferedReader is a resource that must be closed when the program is complete: example:

try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } // Automatic release, execute the close method.Copy the code

6. The appendix

Mybatis can be easily used with a variety of logging framework, it has a log factory class, can tell the specific operation of logging delegated to the agent to perform, support the following several implementations:

SLF4J
Apache Commons Logging
Log4j 2
Log4j
JDK logging
Copy the code

To do this, we need to modify the configuration file mybatis-config.xml:

<configuration>
  <settings>
    ...
    <setting name="logImpl" value="LOG4J"/>
    ...
  </settings>
</configuration>
Copy the code

If the package name of your class is cn.zyfvir, create a new log4j.properties configuration file to set up log4j.

Log4j. rootLogger=ERROR, Stdout # MyBatis logging configuration log4j. Logger. Cn.. Zyfvir = TRACE # console output log4j appenders. Stdout = org.. Apache log4j. ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%nCopy the code
  • Note log4j.logger.cn.zyfvir=TRACE above, which turns on the TRACE log for SQL execution.

Reference: mybatis.org/mybatis-3/z…

Example of creating a database:

CREATE TABLE country
(
  id int NOT NULL AUTO_INCREMENT,
  countryName varchar(255) NULL,
  countryCode varchar(255) NULL,
  PRIMARY KEY (id)
);

INSERT country(countryName,countryCode) values('china',"cn"), ('english',"en");
Copy the code

The complete POM.xml file.

<? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > The < modelVersion > 4.0.0 < / modelVersion > < groupId > cn. Zyfvir < / groupId > < artifactId > mybatisdemo1 < / artifactId > < version > 1.0 - the SNAPSHOT < / version > < dependencies > < the dependency > < groupId > org. Mybatis < / groupId > <artifactId>mybatis</artifactId> <version>3.3.1</version> </dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.44</version> </dependency> </dependencies> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins>  </build> </project>Copy the code

My code examples are on Github, here: github.com/vir56k/java… Github.com/vir56k/java…

7. The appendix

  • Mybatis website: blog.mybatis.org/
  • Mybatis products and documentation: blog.mybatis.org/p/products….
  • Mybatis code generator: mybatis.org/generator/

Reference: 8.

Mybatis.org/mybatis-3/z…

Docs.oracle.com/javase/tuto…