Mybatis study notes

Posted by Isityou on Mon, 04 Oct 2021 23:05:02 +0200

Mybatis study notes

This article is to watch the UP master crazy God of station B say about Video of Mybatis explanation , reference Official documents of Mybatis And CSDN bloggers Black heart white lotus Personal Mybatis notes sorted out by relevant articles. Due to the author's limited ability, there are inevitable mistakes in the article. You are welcome to comment on the Corrigendum and discuss it together!

1. Introduction to Mybatis

1.1 what is Mybatis

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

  • MyBatis eliminates almost all JDBC code and the work of setting parameters and obtaining result sets.

  • MyBatis can configure and map primitive types, interfaces and Java POJO s (Plain Old Java Objects) to records in the database through simple XML or annotations.

  • Maven warehouse

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    
  • Chinese documents: link

  • GitHub: link

1.2 data persistence

  • Persistence: the process of transforming program data from transient state to persistent state
  • Reason: memory is lost immediately after power failure, and the price of memory module is expensive
  • Implementation mode: I/O file operation, database storage (JDBC Technology)

1.3 durable layer

  • Code block that completes the persistence work
  • Layer can make the boundaries of implementing different functional codes obvious
  • Dao layer / Mapper layer

1.4 why do I need to use Mybatis

  • Traditional JDBC code is too complex
  • The semi-automatic framework can help programmers store data into the database more easily
  • It's OK not to use Mybatis. There's no high or low technology

2. The first Mybatis program

2.1 construction environment

Build database

New project

  1. Create a normal Maven project

  2. Delete the src directory (you can make this project a parent project and then create a child project)

  3. Import Maven dependency in pom.xml file

    <!--Import dependency-->
        <dependencies>
            <!--Mysql drive-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.25</version>
            </dependency>
            <!--Mybatis-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.6</version>
            </dependency>
            <!--Junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
  4. Right click the project name to create a Module module

2.2 create Module

  • Write the core configuration file of Mybatis (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">
    <!--Core profile-->
    <configuration>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306 / database name? useSSL=true& useUnicode=true& characterEncoding=utf-8"/>
                    <property name="username" value="Database user name"/>
                    <property name="password" value="Database password"/>
                </dataSource>
            </environment>
        </environments>
    </configuration>
    
  • Write Mybatis tool class file (MybatisUtils.java)

    public class MybatisUtils {
        private static SqlSessionFactory sqlSessionFactory;
    
        //Get SqlSessionFactory object using Mybatis
        static {
            InputStream inputStream = null;
            try {
                String resource = "mybatis-config.xml";
                inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        /**
         * SqlSession Provides all the methods required to execute SQL commands in the database
         */
        public static SqlSession getSqlSession() {
            return sqlSessionFactory.openSession();
        }
    }
    

2.3 coding

  • Entity class pojo / Bean

  • Dao interface (UserMapper.java)

    public interface UserMapper {
        /**
         * Query users by user ID
         * @param id User ID
         * @return All user information
         */
        User getUserById(int id);
    }
    
  • Interface implementation file (UserMapper.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: bind a corresponding namespace mapper Interface-->
    <mapper namespace="com.sit.mapper.UserMapper">
        <select id="getUserById" parameterType="int" resultType="com.sit.pojo.User">
            select * from mybatis.user where id = #{id}
        </select>
    </mapper>
    
  • test

    junit test

    @Test
    public void getUserById() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
    
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
    
        sqlSession.close();
    }
    
  • Possible problems

    org.apache.ibatis.binding.BindingException: Type interface com.sit.mapper.UserMapper is not known to the MapperRegistry.
    

    resolvent:

    Add the following code to the pop.xml file:

    <!--stay build Medium configuration resources,Prevent resource export failure-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
    

3. Basic CRUD operation

3.1 Namespace

The package name of the namespace in the UserMapper.xml file needs to be consistent with the package name of the Dao/Mapper interface!

<mapper namespace="com.sit.mapper.UserMapper">.....</mapper>

3.2 query select

  1. Add method to interface
public interface UserMapper {
    /**
     * Get user list
     * @return User list
     */
    List<User> getUserList();
}
  1. Write SQL statements in the corresponding Mapper.xml file

    <select id="getUserList" resultType="com.sit.pojo.User">
            select * from mybatis.user
    </select>
    
    • id: the method name in the corresponding namespace
    • resultType: return value type of sql statement execution
    • parameterType: parameter type
  2. test

    @Test
    public void getUserList() {
        //1. Get sqlSession
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //2. Execute sql statement
        try{
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = userMapper.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }
        } finally {
            //3. Close sqlSession
            sqlSession.close();
        }
    }
    

3.3 add insert

  1. Add method to interface

    /**
    * Add user
    * @param user New user information
    * @return Insert successfully
    */
    int addUser(User user);
    
  2. Write SQL statements in the corresponding Mapper.xml file

    <insert id="addUser" parameterType="com.sit.pojo.User">
        insert into mybatis.user(id, name, pwd) VALUES (#{id}, #{name}, #{pwd})
    </insert>
    
  3. test

    @Test
    public void addUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int res = mapper.addUser(new User(4, "Xiao Wang", "666666"));
        if (res > 0) System.out.println("User added successfully! ");
        //Add, delete and modify transactions that must be submitted
        sqlSession.commit();
        sqlSession.close();
    }
    

3.4 update - Update

  1. Add method to interface

    /**
    * Update user information by user ID
    * @param user New user information
    * @return Modified successfully
    */
    int updateUserById(User user);
    
  2. Write SQL statements in the corresponding Mapper.xml file

    <update id="updateUserById" parameterType="com.sit.pojo.User">
        update mybatis.user set name = #{name}, pwd = #{pwd} where id = #{id}
    </update>
    
  3. test

    @Test
    public void updateUserById() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int res = mapper.updateUserById(new User(5, "Xiao Yang", "987654"));
        if(res > 0) {
            System.out.println("User modified successfully! ");
        }
        //Add, delete and modify transactions that must be submitted
        sqlSession.commit();
        sqlSession.close();
    }
    

3.5 delete - delete

  1. Add method to interface

    /**
    * Delete user information by user ID
    * @param id User ID
    * @return Successfully deleted
    */
    int deleteUserById(int id);
    
  2. Write SQL statements in the corresponding Mapper.xml file

    <delete id="deleteUserById" parameterType="int">
        delete from mybatis.user where id = #{id}
    </delete>
    
  3. test

    @Test
    public void deleteUserById() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int res = mapper.deleteUserById(4);
        if(res > 0) {
            System.out.println("User deleted successfully! ");
        }
        //Transactions need to be committed for addition, deletion and modification
        sqlSession.commit();
        sqlSession.close();
    }
    

3.6 precautions

Add, delete and modify operations must commit transactions!!!

sqlSession.commit();

3.7 fuzzy query

  1. When Java code is executed, pass wildcard%%

    List<User> userList = mapper.getUserLike("%king%");
    
  2. Using wildcards in sql splicing

    select * from user where name like "%"#{value}"%"
    

3.8 universal Map

When there are too many attributes of entity classes or fields in the database, you should consider using Map

  1. UserMapper.java

    //Insert user with universal Map
    public void addUser2(Map<String,Object> map);
    
  2. UserMapper.xml

    <!--Pass through map of key You can directly retrieve the attribute value in the object -->
    <insert id="addUser2" parameterType="map">
        insert into user (id,name,password) values (#{userid},#{username},#{userpassword})
    </insert>
    
  3. test

    @Test
    public void addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("userid",4);
        map.put("username","Xiao Wang");
        map.put("userpassword","789789");
        mapper.addUser2(map);
        //Commit transaction
        sqlSession.commit();
        //close resource
        sqlSession.close();
    }
    

4. Mybatis configuration resolution

4.1 core configuration file

  • mybatis-config.xml

  • The configuration file of Mybatis contains the settings and attribute information of Mybatis behavior.

    configuration(Configuration)
        properties(Properties)
        settings(Settings)
        typeAliases(Type alias)
        typeHandlers(Type (processor)
        objectFactory(Object factory)
        plugins(Plug in)
        environments(Environment configuration)
        	environment(Environment variables)
        		transactionManager(Transaction manager)
        		dataSource((data source)
        databaseIdProvider(Database (vendor ID)
        mappers(Mapper)
    

4.2 environment configuration

  • Mybatis can configure multiple environments, but only one environment can be selected for each SqlSessionFactory instance.
  • The default transaction manager of Mybatis is JDBC, and the connection pool is POOLED

4.3 properties

  • You can reference the configuration file through the properties attribute;
  • Properties can be configured externally and can be replaced dynamically (for example, a typical Java property file [db.properties]);
  • Properties can also be set in child elements of the properties element.
  1. Write a configuration file db.properties

    driver=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306 / database name? Userssl = true & useunicode = true & characterencoding = UTF-8 & servertimezone = UTC
    username=user name
    password=password
    
  2. Import in core configuration file

    <!--Reference external configuration file-->
    <properties resource="db.properties">
        <property name="username" value="user name"/>
        <property name="password" value="password"/>
    </properties>
    

    Note: if the external file (for example: db.properties) and the core configuration file (mybatis-config.xml) have the same fields, the attribute values in the external configuration file are preferred.

4.4 type aliases

  • You can set an abbreviated name for a Java type, which is only used for XML configuration;
  • The purpose is to reduce redundant fully qualified class name writing.
<!--You can alias an entity class-->
<typeAliases>
    <typeAlias type="com.sit.pojo.User" alias="User"/>
</typeAliases>

You can also specify a package. For each Java Bean in the package com.sit.pojo, if there is no annotation, the first lowercase unqualified class name of the bean will be used as its alias. For example, the alias of com.sit.pojo.User is user; if there is annotation, the alias is its annotation value.

<typeAliases>
    <package name="com.sit.pojo"/>
</typeAliases>
  • When there are few entity classes, use the first method (you can customize the alias);
  • If there are many entity classes, the second method of scanning packages is used.

4.5 Settings

  • The extremely important adjustment settings in Mybatis will change the runtime behavior of Mybatis.
<settings>
        <!--Implementation of standard log factory-->
<!--    <setting name="logImpl" value="STDOUT_LOGGING"/>    -->
    	<!--LOG4J Implementation of log factory-->
    	<setting name="logImpl" value="LOG4J"/>
        <!--Turn on hump naming conversion-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    	<!--Explicitly turn on global cache(It is already on by default)-->
        <setting name="cacheEnabled" value="true"/>
</settings>

4.6 other configurations

4.7 mappers

MapperRegistry: register and bind Mapper files;

Method 1: register with xml file binding [recommended]

<!--every last Mapper.xml All need to be in MyBatis Register in core profile-->
<mappers>
    <mapper resource="com/sit/mapper/UserMapper.xml"/>
</mappers>

Method 2: register with class file binding

<!--every last Mapper.xml All need to be in MyBatis Register in core profile-->
<mappers>
    <mapper class="com.sit.mapper.UserMapper"/>
</mappers>

Note:

  • Interface and its Mapper configuration file must have the same name
  • Interface and its Mapper configuration file must be under the same package

Method 3: inject using packet scanning

<mappers>
    <package name="com.sit.mapper"/>
</mappers>

4.8 scope and lifecycle


Scope and lifecycle are critical, and incorrect use can lead to serious concurrency problems.

SqlSessionFactoryBuilder:

  • Once SqlSessionFactory is created, it is no longer needed
  • Belongs to local variable

SqlSessionFactory:

  • It can be imagined as: database connection pool
  • Once SqlSessionFactory is created, it should always exist during the operation of the application. There is no reason to discard it or re create another instance;
  • The best scope of SqlSessionFactory is the application scope;
  • The simplest is to use singleton mode or static singleton mode.

SqlSession:

  • Imagine a request to connect to the connection pool
  • The SqlSession instance is not thread safe, so it cannot be shared, so its best scope is the request or method scope;
  • It needs to be closed in time after use, otherwise it will occupy resources all the time!

Each Mapper in the diagram represents a specific business!

5. Log

5.1 log factory

If an exception occurs in a database operation, the log is the best assistant for troubleshooting!

Once: South, debug

Now: log factory

  • SLF4J
  • LOG4J [Master]
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING [mastering]
  • NO_LOGGING

Set the specific log in Settings of mybatis-config.xml

STDOUT_ Implementation of logging standard log factory

<settings>
        <!--Implementation of standard log factory-->
	    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

5.2 LOG4J

What is Log4j?

  • Log4j is an open source project of Apache. By using log4j, you can control that the destination of log information transmission is console, file and GUI components;
  • You can also control the output format of each log;
  • By defining the level of each log information, the log generation process can be controlled in more detail;
  • It can be flexibly configured through a configuration file without modifying the application code.
  1. First, import the dependency package of LOG4J in the pop.xml file

    <dependencies>
    		<!--LOG4J-->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
    </dependencies>    
    
  2. Create a log4j.properties file in the resources folder for configuration

    #Output the log information with the level of DEBUG to the two destinations of console and file. The definitions of console and file are in the following code
    log4j.rootLogger=DEBUG,console,file
    
    #Settings related to console output
    log4j.appender.console = org.apache.log4j.ConsoleAppender
    log4j.appender.console.Target = System.out
    log4j.appender.console.Threshold=DEBUG
    log4j.appender.console.layout = org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
    
    #Settings related to file output
    log4j.appender.file = org.apache.log4j.RollingFileAppender
    log4j.appender.file.File=./log/log4j.log
    log4j.appender.file.MaxFileSize=10mb
    log4j.appender.file.Threshold=DEBUG
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=[%p][20%d{yy-MM-dd}][%c]%m%n
    
    #Log output level
    log4j.logger.org.mybatis=DEBUG
    log4j.logger.java.sql=DEBUG
    log4j.logger.java.sql.Statement=DEBUG
    log4j.logger.java.sql.ResultSet=DEBUG
    log4j.logger.java.sql.PreparedStatement=DEBUG
    
  3. Configure Log4j as the implementation of log factory in mybatis-config.xml core configuration file

    <settings>
            <!--LOG4J Implementation of log factory-->
            <setting name="logImpl" value="LOG4J"/>
    </settings>
    
  4. Test run of Log4j

Simple use

  1. In the test class to use Log4j, import the package org.apache.log4j.Logger

  2. Log object. The parameter is the class of the current class

    static Logger logger = Logger.getLogger(UserMapperTest.class);
    
  3. log level

    logger.info("info: Entered testLog4j");
    logger.debug("debug: Entered testLog4j");
    logger.error("erro: Entered testLog4j");
    
  4. After that, you can view the log file information in the log folder

6. Pagination

6.1 why pagination?

  • Reduce data processing

6.2 using Limit paging

Syntax: SELECT * from tableName limit startIndex,pageSize
 For example: SELECT  * from user limit 3 #[0,n-1]
  1. Interface

    List<User> getUsersByLimit(Map<String,Integer> map);
    
  2. Mapper.xml

    <!--paging-->
    <select id="getUsersByLimit" parameterType="map" resultMap="UserMap">
    	select * from mybatis.user limit #{startIndex},#{pageSize}
    </select>
    
  3. test

    @Test
    public void getUsersByLimit(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("startIndex",0);
        map.put("pageSize",2);
    
        List<User> userList = mapper.getUsersByLimit(map);
        for (User user : userList) {
            System.out.println(user);
        }
    
        sqlSession.close();
    }
    

6.3 rowboundaries paging

  1. Interface

    List<User> getUsersByRowBounds();
    
  2. Mapper.xml

    <!--Pagination 2-->
    <select id="getUsersByRowBounds" resultMap="UserMap">
    	select * from mybatis.user
    </select>
    
  3. test

    @Test
    public void getUsersByRowBounds(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
    
        //RowBounds implementation
        RowBounds rowBounds = new RowBounds(0, 2);
    
        //Paging through java code level
        List<User> userList = sqlSession.selectList("com.sit.mapper.UserMapper.getUsersByRowBounds",null,rowBounds);
    
        for (User user : userList) {
            System.out.println(user);
        }
    
        sqlSession.close();
    }
    

6.4 Paging plug-in

7. Dynamic SQL

Dynamic SQL refers to generating different SQL statements according to different conditions.

The so-called dynamic SQL is essentially an SQL statement, but we can execute a logical code at the SQL level.

7.1 construction environment

CREATE TABLE `mybatis`.`blog`  (
  `id`  VARCHAR(10) NOT NULL AUTO_INCREMENT COMMENT 'Blog id',
  `title` varchar(30) NOT NULL COMMENT 'Blog title',
  `author` varchar(30) NOT NULL COMMENT 'Blogger',
  `create_time` datetime NOT NULL COMMENT 'Creation time',
  `views` int(30) NOT NULL COMMENT 'Views',
  PRIMARY KEY (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;

Create a base project

  1. Guide Package

  2. Write configuration file

  3. Writing entity classes

    package com.sit.pojo;
    
    import java.util.Date;
    
    /**
     * @version : v1.0
     * @function : Blog class
     */
    public class Blog {
        private String id;
        private String title;
        private String author;
        private Date createTime;
        private int views;
    
        public Blog() {
        }
    
        public Blog(String id, String title, String author, Date createTime, int views) {
            this.id = id;
            this.title = title;
            this.author = author;
            this.createTime = createTime;
            this.views = views;
        }
    
        //Omit the get() and set() methods of each attribute
    
        @Override
        public String toString() {
            return "Blog{" +
                    "id=" + id +
                    ", title='" + title + '\'' +
                    ", author='" + author + '\'' +
                    ", createTime=" + createTime +
                    ", views=" + views +
                    '}';
        }
    }
    
  4. Write Mapper interface and Mapper.XML file corresponding to entity class

7.2 if

<select id="queryBlogIF" parameterType="map" resultType="Blog">
    select * from mybatis.blog where 1=1
    <if test="title != null">
        and title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</select>

7.3 choose(when, otherwise)

<select id="queryBlogsByChoose" parameterType="map" resultType="Blog">
    select * from mybatis.blog
    <where>
        <choose>
            <when test="title != null">
                title=#{title}
            </when>
            <when test="author != null">
                and author=#{author}
            </when>
            <otherwise>
                views=#{views}
            </otherwise>
        </choose>
    </where>
</select>

7.4 trim(where, set)

<select id="queryBlogsByIf" parameterType="map" resultType="Blog">
    select * from mybatis.blog
    <where>
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
</select>
<update id="updateBlog" parameterType="map">
    update mybatis.blog
    <set>
        <if test="title != null">title=#{title},</if>
        <if test="author != null">author=#{author},</if>
    </set>
    where views=#{views}
</update>

8. Cache

8.1 introduction

1. What is cache?

  • Temporary data in memory;
  • The data frequently queried by users is placed in the cache (memory), and when users query the data, they do not need to query from the disk (relational database query file), but instead query from the cache, which improves the query efficiency and solves the performance problem of high concurrency system.

2. Why cache?

  • Reduce the number of interactions with the database, reduce system overhead and improve system efficiency.

3. What kind of data can be cached?

  • Frequently queried and infrequently changed data.

8.2 Mybatis cache

  • Mybatis includes a very powerful query caching feature that makes it easy to customize and configure caching. Caching can greatly improve query efficiency.
  • Two levels of cache are defined by default in the Mybatis system: L1 cache and L2 cache
    • By default, only L1 cache is on. (SqlSession level cache, also known as local cache)
    • L2 cache needs to be manually enabled and configured. It is a namespace level cache.
    • In order to improve scalability, Mybatis defines the Cache interface Cache. We can customize the L2 Cache by implementing the Cache interface.

8.3 L1 cache

  • The data queried during the same session with the database will be placed in the local cache;
  • In the future, if you need to obtain the same data, you can get it directly from the cache. There is no need to query the database.

8.3.1 test steps

  1. Open log

  2. Query the same record twice in a SqlSession

    @Test
    public void testCacheLevel1() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        System.out.println("===================================");
        User user2 = mapper.getUserById(1);
        System.out.println(user2);
        System.out.println("===================================");
        System.out.println(user == user2);
        System.out.println("===================================");
        sqlSession.close();
    }
    
  3. View log output

8.3.2 cache invalidation

  1. Query different data

  2. Added, deleted and modified (the cache will be refreshed because the original data will be changed!)

  3. Query different Mapper.xml

  4. Manual cache cleanup

    @Test
    public void testCacheLevel1() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        
        User user = mapper.getUserById(1);
        System.out.println(user);
        System.out.println("===================================");
        
        //Manual cache cleanup
        sqlSession.clearCache();
        
        User user2 = mapper.getUserById(1);
        System.out.println(user2);
        System.out.println("===================================");
        
        System.out.println(user == user2);
        System.out.println("===================================");
        sqlSession.close();
    }
    

    test result

Summary:

The L1 cache is enabled by default and is valid only once in a SqlSession, that is, at the stage from getting the connection to closing the connection, the L1 cache is equivalent to a Map.

8.4 L2 cache

  • L2 cache is also called global cache, which is based on namespace level cache
  • Working mechanism
    • A session queries a piece of data, and the data will be placed in the first level cache of the current session;
    • If the current session is closed, the corresponding L1 cache will disappear, and the data in the L1 cache will be saved to the L2 cache;
    • The new session query information can get the content from the L2 cache;
    • The data found in different mapper.xml will be placed in their corresponding cache (map).

8.4.1 use steps

  1. Open the global cache in mybatis-config.xml

    <settings>
        <!--Explicitly turn on global cache(It is already on by default)-->
        <setting name="cacheEnabled" value="true"/>
    </settings>
    
  2. Open in mapper.xml where you want to use L2 cache

    <!--At present Mapper.xml Using L2 cache in-->
    <cache/>
    

    You can also customize parameters

    <!--At present Mapper.xml Using L2 cache in-->
    <cache
    	eviction="FIFO"
        flushInterval="60000"
        size="512"
        readOnly="true"/>
    
  3. test

    If there are no custom parameters, an error will be reported. You need to serialize the entity class!

    Cause: java.io.NotSerializableException: com.sit.pojo.User
    

    Solution

    public class User implements Serializable {...}
    

Summary:

  • All data will be put in the first level cache first;
  • As long as the L2 cache is enabled, it is valid under the same mapper.xml;
  • Only when the session is submitted or closed, the data will be submitted to the L2 cache.

8.5 cache principle

9. Possible problems

9.1 inconsistency between attribute name and field name

Fields in the database

Entity class attribute of POJO in new project

public class User {
    private int id;
    private String name;
    private String password;
}

Test problems

resolvent

  1. Alias

    <select id="getUserById" parameterType="int" resultType="user">
          select id,name,pwd as password from mybatis.user where id = #{id}
    </select>
    
  2. Result set mapping (ResultMap)

    <!--  Result set mapping  -->
        <resultMap id="UserMap" type="User">
            <!--column Fields in the database, property Properties in entity classes-->
            <result column="id" property="id" /> <!--Can be omitted-->
            <result column="name" property="name" /> <!--Can be omitted-->
            <result column="pwd" property="password" />
        </resultMap>
    
        <select id="getUserById" parameterType="int" resultMap="UserMap">
            select * from mybatis.user where id = #{id}
        </select>
    

9.2 resource export failure

Configure resources in the build of pop.xml

<build>
	<resources>
		<resource>
           	<directory>src/main/resources</directory>
            <includes>
               	<include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>
  1. Result set mapping (ResultMap)

    <!--  Result set mapping  -->
        <resultMap id="UserMap" type="User">
            <!--column Fields in the database, property Properties in entity classes-->
            <result column="id" property="id" /> <!--Can be omitted-->
            <result column="name" property="name" /> <!--Can be omitted-->
            <result column="pwd" property="password" />
        </resultMap>
    
        <select id="getUserById" parameterType="int" resultMap="UserMap">
            select * from mybatis.user where id = #{id}
        </select>
    

9.2 resource export failure

Configure resources in the build of pop.xml

<build>
	<resources>
		<resource>
           	<directory>src/main/resources</directory>
            <includes>
               	<include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

Topics: Java Database Mybatis SSM