Getting started with mybatis

Time:2020-8-14

Mybatis usage scenarios

In mybatis development, most of our efforts were focused on SQL mapping configuration files. Although mybatis requires developers to configure their own SQL statements and mybatis to implement the mapping relationship, such projects can adapt to changing project requirements. Therefore, the scenario of using mybatis is that the SQL optimization requirements are relatively high, or the project requirements or business often change.

Overall architecture of mybatis

  • Data source profile
  • SQL mapping profile
  • Conversation factory and conversation

Data source profile

The data source is configured in SqlMapConfig.xml (the file name can be changed) in the configuration file, which includes the database connection address, database user name, password and other parameters.

SQL mapping profile

That is, SQL is configured in a separate configuration file Mapper.xml (the file name can be changed).

Conversation factory and conversation

The session factory is the sqlsessionfactory class. According to the database configuration information and SQL statement configuration information, sqlsessionfactory can generate sqlsession session session instance classes that can connect to the database and interact with it.

Write log output environment configuration file

Create a log4j.properties blank property file:

log4j.rootLogger = debug, stdout  
log4j.appender.stdout = org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern = %5p \[%t\] - %m%n

Write database connection pool configuration file

Write an entry-level sqlmapconfig configuration file, which is the global configuration file of mybatis:

<? XML version = "1.0" encoding = "UTF-8"? > <! -- specify XML version information and encoding format -- >  
<!DOCTYPE  configuration  
  PUBLIC  "-//mybatis.org//DTD Config 3.0//EN"  
  " http://mybatis.org/dtd/mybatis-3-config.dtd "> <! -- use DTD documents to define types -- >  
<configuration>  
    <settings>  
        < setting name = "logimpl" value = "log4j" / > <! -- configure the log output mode logimpl to log4j -- >
    </settings>  
    <! -- after integrating with spring, the environment configuration will be abolished, and the data source configuration in mybatis can be managed by spring -- >
  <environments default="development">  
        <environment id="development">  
            <! -- using JDBC transaction management -- >  
  <transactionManager type="JDBC" />  
            <! -- database connection pool -- >  
  <dataSource type="POOLED">  
                <property name="driver" value="org.gjt.mm.mysql.Driver"/>  
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis\_test?characterEncoding=utf-8"/>  
                <property name="username" value="root"/>  
                <property name="password" value="123456"/> 
            </dataSource>  
        </environment>  
    </environments>  
 <! -- to parse mapper file, it must be placed at the end of the configuration tag -- >  
 <! -- parse mapper file -- >  
  <mappers>  
        <mapper resource="sqlmap/UserMapper.xml"/>  
  </mappers>  
</configuration>

Write SQL mapping configuration file

All configurations are packaged inmapperLabel alignment,mapperTaggednamespaceThe function of attribute is to classify the SQL Management and realize the SQL isolation of different business.

SQL statements can be divided into add, delete, modify and query. The corresponding tag pairs areinsertdeleteupdate, andselect

Each SQL configuration tag has parametertype, parametermap, resulttype, resultclass and resultmap attributes, representing input parameter type, input parameter set, result type, result class and result set respectively.

Create a new one UserMapper.xml A query statement is configured here

<? XML version = "1.0" encoding = "UTF-8"? > <! -- specify XML version information and encoding format -- >  
<!DOCTYPE  mapper  
  PUBLIC  "-//mybatis.org//DTD Mapper 3.0//EN"  
  " http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <! -- use DTD documents to define types -- >  
  
<mapper namespace="test">  
    <select id="findUserById" parameterType="int" resultType="cn.com.mybatis.po.User">  
        select * from user where id=#{id}  
    </select>  
</mapper>

idUnique identifier of the select tag of the property.
In the SQL configuration of mybatis,#{}Mark a place holder when accepting a simple type,#{}You can only write “value” in. If you accept JavaBeans,#{}The property name of the JavaBean to be filled in.

After writing the SQL mapping file, in order to enable the mybatis resource file loading class to parse mapper file, you must configure the SqlMapConfig.xml At the end of the configuration tab in, the configuration information is as follows:

  <mappers>  
        <mapper resource="sqlmap/UserMapper.xml" />  
  </mappers>

Write data interaction class and test case

Persistent entity class

The one-to-one correspondence of a class field in a Java persistent variable is a class field in a java database.

package cn.com.mybatis.po;  
  
import java.io.Serializable;  
import java.util.Date;  
  
public class User implements Serializable{  
    private int id;  
    private String username;  
    private String password;  
    private String gender;  
    private String email;  
    private String province;  
    private String city;  
    private Date birthday;  
  
    public int getId() {  
        return id;  
    }  
    public void setId(int id) {  
        this.id = id;  
    }  
    public String getUsername() {  
        return username;  
    }  
    public void setUsername(String username) {  
        this.username = username;  
    }  
    //The remaining get and set methods are omitted
}

Database interaction class

Create a class that can obtain sqlsession (i.e. database interaction object)

package cn.com.mybatis.datasource;  
  
import java.io.IOException;  
import java.io.InputStream;  
  
import org.apache.ibatis.io.Resources;  
import org.apache.ibatis.session.SqlSession;  
import org.apache.ibatis.session.SqlSessionFactory;  
import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
  
public class DataConnection {  
    //Mubatis configuration file  
    private String resource="SqlMapConfig.xml";  
    private SqlSessionFactory sqlSessionFactory;  
    private SqlSession sqlSession;  
  
    public SqlSession getSqlSession() throws IOException {  
        InputStream inputStream = Resources.getResourceAsStream(resource);  
        //Create a session factory and pass in mybatis configuration file information  
        sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);  
        sqlSession=sqlSessionFactory.openSession();  
        return sqlSession;  
    }  
}

Write test cases

Write a user data with ID 1 from the database

package cn.com.mybatis.test;  
  
import cn.com.mybatis.datasource.DataConnection;  
import cn.com.mybatis.po.User;  
import org.apache.ibatis.session.SqlSession;  
import org.junit.jupiter.api.DynamicTest;  
import org.junit.jupiter.api.Test;  
  
import java.io.IOException;  
import java.util.List;  
  
public class MyBatisTest {  
    public DataConnection dataConnection = new DataConnection();  
  
    @Test  
  public void TestSelect() throws IOException{  
        SqlSession sqlSession = dataConnection.getSqlSession();  
        User user = sqlSession.selectOne("test.findUserById", 1);  
        System.out.println(user.getUsername());  
        sqlSession.close();  
    }  

Data operation of entry program

Example of fuzzy query

stay UserMapper.xml Configure SQL mapping in configuration file:

<select id="findUserByUsername" parameterType="String" resultType="cn.com.mybatis.po.User">  
    select * from user where username like '%${value}%'  
</select>

In mybatis, in the SQL configuration fileselectOf SQL statement in tag alignment${}If the SQL string is not decorated, it will be injected into the SQL string${}Only value can be used to represent parameters in.

Write a new test method

@Test  
public void TestFuzzySearch() throws IOException{  
    SqlSession sqlSession = dataConnection.getSqlSession();  
    List<User> userList =  sqlSession.selectList (" test.findUserByUsername (LI);  
    for (var user:userList) {  
        System.out.println( user.getUsername());  
    }  
}

New sample

Add a new user:

<insert id="insertUser" parameterType="cn.com.mybatis.po.User">  
    insert into user(username,password,gender,birthday,email,province,city)  
      value(#{username},#{password},#{gender},#{birthday,jdbcType=DATE},  
      #{email},#{province},#{city})  
</insert>

New test method:

@Test  
public void TestInsert() throws Exception{  
    SqlSession sqlSession = dataConnection.getSqlSession();  
    User user = new User();  
    user.setUsername("xiaoxiao");  
    sqlSession.insert("test.insertUser", user);  
    sqlSession.commit();  
    sqlSession.close();  
}

Add a new user and return the primary key information corresponding to the entry:

<insert id="insertUser" parameterType="cn.com.mybatis.po.User" useGeneratedKeys="true" keyProperty="id">  
    insert into user(username,password,gender,birthday,email,province,city)  
      value(#{username},#{password},#{gender},#{birthday,jdbcType=DATE},  
      #{email},#{province},#{city})  
</insert>

useGeneratedKeysIndicates the use of an auto increment primary key, and keyproperty is the property name of a Java object. After the insert statement is executed, the self growing ID value is automatically assigned to the attribute ID of the object user.
There is also a way to obtain the auto increment primary key

<insert id="insertUser" parameterType="cn.com.mybatis.po.User">  
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">  
            SELECT LAST_INSERT_ID()  
        </selectKey>  
        insert into user(username,password,gender,birthday,email,province,city) 
            value(#{username},#{password},#{gender},#{birthday,jdbcType=DATE},
            #{email},#{province},#{city})  
</insert>

SELECT LAST_INSERT_ID()It is used to query the last auto increment primary key of MySQL,orderThe parameter indicates whether the execution time of the SQL function relative to the insert statement is before or after. After the insert statement is executed, the self growing ID value is automatically assigned to the attribute ID of the object user.

Examples of deletion and modification

SQL configuration:

<! -- delete user -- >  
    <delete id="deleteUser" parameterType="java.lang.Integer">  
        delete from user where id=#{id}  
    </delete>  
    <! -- modify user -- >  
    <update id="updateUserName" parameterType="cn.com.mybatis.po.User">  
        update user set username=#{username} where id=#{id}  
    </update>

Two new test methods are added

@Test  
public void TestDelete() throws Exception{  
    SqlSession sqlSession = dataConnection.getSqlSession();  
    sqlSession.delete("test.deleteUser", 7);  
    sqlSession.commit();  
    sqlSession.close();  
}  
  
@Test  
public void Testupdate() throws Exception{  
    SqlSession sqlSession = dataConnection.getSqlSession();  
    User user = new User();  
    user.setId(4);  
    user.setUsername ("Sun Xiao");  
    sqlSession.update("test.updateUserName", user);  
    sqlSession.commit();  
    sqlSession.close();  
}

So far, all the programming and development work of the entry program has been completed.