When I learned project engineering yesterday, I found that I used mybatis a lot. I also used mybatis before, so I thought I’d better make notes and record by myself. Mybatis is a data access layer framework. Like most similar frameworks, Mybatis saves developers from using JDBC underlying database operations for a large part of the code. With Mybatis, developers only need to write SQL in the configuration file and declare the mapping between the SQL return value and Java type. Mybatis also supports interface programming. If you integrate MyBatis with Spring, you will find that you do not need to declare the implementation class for the interface to operate on the database. All you need to do is declare the relevant class in the XML file to tell MyBatis. Mybatis will help us deal with operations such as linking to the database.

I will not explain the relevant theoretical knowledge of Mybatis below, because the official website is very clear, and WHAT I need to do is to explain the three levels of application mode, which are using MyBatis in programming mode, using MyBatis based on annotations, integrating MyBatis with Spring, All projects are built using Maven.

For demonstration purposes, I have posted the relevant database scripts and some common components such as mapper interface:

create database test;
CREATE TABLE `test`.`student` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `NAME` VARCHAR(45) NULL,
  `AGE` INT NULL,
  `ADDRESS` VARCHAR(45) NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `id_UNIQUE` (`id` ASC));
Copy the code

StudentMapper. Java interface

package com.wokao666.mappers; import java.util.List; import java.util.Map; import com.wokao666.entity.Student; /** ** The class StudentMapper. ** Description: StudentMapper ** @author: huangjiawei * @since: June 7, 2018 * @version:$Revision$ $Date$ $LastChangedBy$
 *
 */
public interface StudentMapper {

    public Student getById(Map<String, Object> param);

    public List<Student> listStudents();
}
Copy the code

The entity class Student. Java

package com.wokao666.entity; /** ** The class Student. ** Description: Student entity ** @author: huangjiawei * @since: June 7, 2018 * @version:$Revision$ $Date$ $LastChangedBy$
 *
 */
public class Student {

    private int id;
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    private String name;
    private String address;
    private int age;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getAddress() {
        return address;
    }
    
    public void setAddress(String address) {
        this.address = address;
    }
    
    public int getAge() {
        return age;
    }
    
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", address=" + address + ", age=" + age + "]";
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    public Student(int id, String name, String address, int age) {
        super();
        this.id = id;
        this.name = name;
        this.address = address;
        this.age = age;
    }
    
    public Student() {}}Copy the code

StudentMapper.xml

<? xml version="1.0" encoding="UTF-8"? > <! DOCTYPE mapper PUBLIC"- / / mybatis.org//DTD Mapper / 3.0 / EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <! -- Namespace configuration, since we may have many mapper, we usually set this value to the fully qualified path of the package name --> <mapper namespace="com.wokao666.mappers.StudentMapper"> <! -- Represents a mapping of your SQL query results to Java types, usually Java beans --> <resultMaptype="com.wokao666.entity.Student" id="studentMap">
        <result property="id" column="ID"/>
        <result property="name" column="NAME" />
        <result property="age" column="AGE" />
        <result property="address" column="ADDRESS"/> </resultMap> <! -- select statement, query by condition, specify parameter type as map --> < SELECT id="getById" resultMap="studentMap" parameterType="java.util.Map">
        select * from Student where id = #{id};
    </select>	
    
    <select id="listStudents" resultMap="studentMap">
        select * from Student;
    </select>
</mapper>
Copy the code

mybatis-config.xml

<? 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> <! -- Property configuration, similar to global variables --> <properties> <property name="driver" value="com.mysql.jdbc.Driver" />
        <property name="url"
            value="jdbc:mysql://localhost:3306/test? serverTimezone=UTC" />
        <property name="username" value="root" />
        <property name="password" value="root"/> </properties> <! You can define multiple environments, such as development, test, pre-production, production --> <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}"/> </dataSource> </environment> </environments> <! <mappers> <mapper resource= <mappers> <mapper resource="StudentMapper.xml" />
    </mappers>
</configuration>
Copy the code

1. Use Mybatis programming mode to operate database

In Mybatis, the program construction starts with a function called SqlSessionFactory. SqlSessionFactory can be built using SqlSessionFactoryBuilder. SqlSessionFactoryBuilder supports building from a stream of configuration files.

pom.xml

<? 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/maven-v4_0_0.xsd"> < modelVersion > 4.0.0 < / modelVersion > < groupId > mybatisTest < / groupId > < artifactId > mybatisTest < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > < packaging > jar < / packaging > < name > mybatisTest < / name > < properties > <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.mybatis</groupId> The < artifactId > mybatis < / artifactId > < version > 3.4.6 < / version > < / dependency > <! -- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> </dependencies> </dependencies> </project>Copy the code

Test.java

package com.wokao666.test; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.wokao666.entity.Student; import com.wokao666.mappers.StudentMapper; /** ** The class Test. ** Description: Programming using mybatis ** @author: huangjiawei * @since: June 8, 2018 * @version:$Revision$ $Date$ $LastChangedBy$* */ public class Test {public static void main(String[] args) throws IOException {// Read our configuration file InputStream input = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(input); Session SqlSession Session = factory.openSession(); // Construct query parameters Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("id", 2); Student stu = session.selectOne("getById", paramMap); System.err.println(stu.toString()); StudentMapper mapper = session.getMapper(studentmapper. class); // Test using the namespace to query a record. System.err.println(mapper.getById(paramMap)); List<Student> stuList = session.selectList("listStudents"); System.err.println(Arrays.toString(stuList.toArray())); }}Copy the code

Program output

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Fri Jun 08 14:50:11 CST 2018 WARN: Establishing SSL connection without server'identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL Connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore forServer certificate verification. Student [ID =2, name=Mike, address= age=24] Student [ID =2, name=Mike, address= [Student [id=2, name=Mike, address= zhejiang, age=24]]Copy the code

Annotation-based Mybatis

This blog post only demonstrates the use of simple SQL, such as more complex SQL (such as associative query join). As we all know, Mybatis recommends that we write SQL statements into all kinds of mapper. XML. When our business is very large, there will undoubtedly be a lot of new XML files in the system, of course, we prefer as few XML files as possible. Mybatis allows developers to use MyBatis based on interfaces and annotations. For some simple SQL, it is not necessary to write it in XML files. Instead, we recommend to write simple SQL in annotations and complex SQL in XML file management.

Mybatis will be used in two ways based on annotations, one is to rewrite the first programming-based method, the second is to use the spring-boot integrated myBatis, of course, the second way is more practical, more close to our real development, or with many developers already use this way.

1. Use of programmatic annotations

Add a new method to the studentMapper. Java interface like this:

package com.wokao666.mappers; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Select; import com.wokao666.entity.Student; /** ** The class StudentMapper. ** Description: StudentMapper ** @author: huangjiawei * @since: June 7, 2018 * @version:$Revision$ $Date$ $LastChangedBy$* */ public interface StudentMapper {// Select();"select * from Student where id=1")
    public Student get();
    
    public Student getById(Map<String, Object> param);
    
    public List<Student> listStudents();

}
Copy the code

Then add this line of code to the end of test.java in the first summary.

System.err.println(mapper.get());
Copy the code
2. Use Mybatis based on spring-boot

Download code: github.com/SmallerCode…

Engineering structure drawing is as follows:

The project is divided into three layers, namely controller, Service and DAO layers, namely the traditional MVC model.

Import project start after MybatisDemoApplication. Java classes, and then the browser enter http://localhost:7000/get.json? Id = 1 can!

Integrate with Spring

Whenever we operate on the database at the application code level, the first thing we need to do is to configure an appropriate data source. The data source can easily configure the URL, driver, USERNAME, password and other parameters of JDBC. C3p0, Druid, c3P0, druid, c3P0, Druid, c3P0, Druid, c3P0, Druid, c3P0, Druid, c3P0, Druid

The key to Spring integration with Mybatis is to add a dependency package, namely:

< the dependency > < groupId > org. Mybatis < / groupId > < artifactId > mybatis - spring < / artifactId > < version > 1.3.1 < / version > </dependency>Copy the code

Website address of the project: www.mybatis.org/spring/zh/i…

Examples of sections 1 and 3 above can be downloaded from github.com/SmallerCode…

If this example code is helpful to you, give a start yo ~~~

To summarize, MyBatis is a data access framework that basically minimizes the need to write low-level JDBC links. It also helps us map database entities to Java objects. Of course, if you want to further study Mybatis, I suggest you go to mybatis official website system learning, Mybatis function is very powerful, if you need to make conditional judgment, Mybatis run you in mapper file SQL using tags such as

to judge, come on, soran, friends, Welcome more exchanges!