Mybatis personal study notes

Posted by simongcc on Thu, 03 Mar 2022 12:38:29 +0100

Mybatis personal summary notes

01 basic information

  1. Mybatis is the SQL mapping framework
  2. This object can be mapped into a row of data in the database
  3. Developers only need to provide sql, process sql through Mybatis, and finally get the List collection or Java objects
  4. Mybatis is a semi-automatic ORM mapping tool, which is called semi-automatic ORM mapping tool because it needs to write SQL manually when querying Association objects or association collection objects

02 defects of traditional JDBC

  1. The frequent creation and release of database connections will cause a waste of system resources, which will affect the performance of the system. If the database connection pool is used, this problem will be solved

Solution: in mybatis config Configure the database connection pool in the XML configuration file and use the connection pool for management

  1. SQL is hard coded in the code, which makes the code difficult to maintain. The actual application of SQL may change greatly. The change of SQL needs to change the Java code

Solution: configure the SQL statement in xxxmapper XML file, separated from java code

  1. There is hard coding when using PreparedStatement to pass parameters to placeholders, because the where conditions of SQL statements are not certain, which may be more or less. Modifying SQL statements and modifying codes makes the system difficult to maintain

Solution: Mybatis automatically maps Java objects to SQL statements

  1. There is hard coding for result set parsing

Solution: Mybatis automatically maps SQL execution results to Java objects

03 advantages and disadvantages of mybatis

3.1 advantages

  1. Programming based on SQL statement is quite flexible and will not have any impact on the existing design of application program or database
  2. SQL statements are written in XML files, which decouples SQL from program code
  3. Compared with JDBC, the amount of code is less, which eliminates a large number of redundant codes in JDBC and does not require manual switch connection
  4. Compatible with multiple databases

3.2 disadvantages

  1. The workload of writing SQL statements is large, especially when there are many fields and associated tables, it is difficult to write SQL statements
  2. SQL statements depend on the database, resulting in poor database migration ability

04 development mode of mybatis

4.1 using native interfaces

4.1.1 add dependency

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.1</version>
</dependency>
<dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.13</version>
</dependency>

4.1.2 create a new database table

4.1.3 create the entity class corresponding to the data table

package com.mybatis.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private String username;
    private String sex;
    private Long phone;
}

4.1.4 create SQL mapping file

The Mybatis framework requires developers to customize SQL statements, which are written in mapper XML file, in actual development, a corresponding mapper will be created for each entity class XML, which defines the SQL to manage the object data

  • namespace: usually set in the form of package + file name of the file
  • The select tag indicates that the query operation is performed
  • The insert tag indicates that the insert operation is performed
  • The update tag indicates that the update operation is performed
  • The delete tag indicates that the delete operation is performed
  • id: the parameters needed to actually call the Mybatis method
  • paramterType: the data type of the parameter when calling the corresponding method
<?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">
<mapper namespace="com.mybatis.dao.UserMapper">
    <select id="getAllStudent" resultType="com.mybatis.model.Student">
        select * from student
    </select>
</mapper>

4.1.5 create Mybatis master configuration file

Partial parameter analysis
<transactionManager type="JDBC"/>

  • JDBC: indicates the commit rollback of the Connection object in JDBC called by the underlying layer of mybatis
  • MANAGED: delegate the transaction processing of mybatis to other containers, a server software and a spring framework

<dataSource type="POOLED">

  • Represents the data source. In the java system, javax is specified sql. Datasoutce interfaces are all data sources, which represent Connection objects.
  • Type of type
    • POOLED: using connection pool, mybatis will create pooldatasource class
    • UPOOLED: do not use Connection pool. Each time you execute sql statement, create a Connection and execute sql. When you close the Connection, mybatis will create an UnPooledDataSource to manage the management of Connection
<?xml version="1.0" encoding="UTF-8" ?>
<!--Constraint file-->
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--to configure Mybatis Operating environment default Is to select one from multiple data sources-->
    <environments default="development">
        <!--A data source, id Unique value-->
        <environment id="development">
            <!--Configure transaction management-->
            <transactionManager type="JDBC"/>
            <!--Configure connection pool-->
            <dataSource type="POOLED">
                <!--Four elements of connecting database-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306 /frame?serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com\mybatis\dao\UserMapper.xml"/>
    </mappers>
</configuration>

4.1.6 create test class

public class Main {
    public static void main(String[] args) throws IOException {
        String config = "mybatis-config.xml";
        //Read the information of the file represented by the path
        InputStream in = Resources.getResourceAsStream(config);
        //Create SqlSession object
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(in);
        SqlSession sqlSession = sessionFactory.openSession();
        Student student = new Student("Page","male","18893694975");
        String statement = "com.mybatis.dao.UserMapper.insertStudent";
        sqlSession.insert(statement,student);
        sqlSession.commit();
        sqlSession.close();
    }
}

4.2 using Mapper agent to realize user-defined interface

4.2.1 add dependency

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.1</version>
</dependency>
<dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.13</version>
</dependency>

4.2.2 create a new database table

4.2.3 create entity class corresponding to data table

package com.mybatis.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private String username;
    private String sex;
    private Long phone;
}

4.2.4 customize Mapper interface

public interface UserMapper {
    List<Student> getAllStudent();
    int save(Student student);
    int deleteByName(String name);
    int update(Student student);
}

4.2.5 create interface mapping file

The statement tag can be selected according to the business executed by SQL. The Mybatis framework will automatically create the proxy object of the interface implementation class according to the rules

rule

  • Mapper. namespace in XML is the full class name of the interface
  • Mapper. The id of the statement in XML is the corresponding method name in the interface
  • Mapper. The parameterType of the statement in XML is consistent with the parameter type of the corresponding method in the interface
  • Mapper. The resultType of the statement in XML is consistent with the return value type of the corresponding method in the interface
<?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">
<mapper namespace="com.mybatis.dao.UserMapper">
    <insert id="save" parameterType="com.mybatis.model.Student">
        insert into student(username,sex,phone) values(#{username},#{sex},#{phone})
    </insert>
    <select id="getAllStudent" resultType="com.mybatis.model.Student">
        select * from student
    </select>
    <update id="update" parameterType="com.mybatis.model.Student">
        update student set phone=#{phone} where username=#{username}
    </update>
    <delete id="deleteByName" parameterType="java.lang.String">
        delete from student where username=#{username}
    </delete>
</mapper>

4.2.6 create Mybatis master configuration file

<?xml version="1.0" encoding="UTF-8" ?>
<!--Constraint file-->
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--to configure Mybatis Operating environment default Is to select one from multiple data sources-->
    <environments default="development">
        <!--A data source, id Unique value-->
        <environment id="development">
            <!--Configure transaction management-->
            <transactionManager type="JDBC"/>
            <!--Configure connection pool-->
            <dataSource type="POOLED">
                <!--Four elements of connecting database-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306 /frame?serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com\mybatis\dao\UserMapper.xml"/>
    </mappers>
</configuration>

4.2.7 create test class

public class Main {
    public static void main(String[] args) throws IOException {
        String config = "mybatis-config.xml";
        //Read the information of the file represented by the path
        InputStream in = Resources.getResourceAsStream(config);
        //Create SqlSession object
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(in);
        SqlSession sqlSession = sessionFactory.openSession();
        Student student = new Student("Page","male","18893694975");
        UserMapper mapper = (UserMapper) sqlSession.getMapper(UserMapper.class);
        // insert
        int save = mapper.save(student);
        // query
        List<Student> allStudent = mapper.getAllStudent();
        // delete
        int i = mapper.deleteByName("Page");
        // to update
        Student s = new Student("Page","male","18893694974");
        int update = mapper.update(s);
        sqlSession.commit();
        sqlSession.close();
    }
}

4.3 configuration log

In order to facilitate us to view the changes of SQL, we can view it in the main configuration file

 <!--control mybatis Global behavior-->
    <settings>
        <!--Set output log-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

05 description of main objects

5.1 Resources class

  1. A class in mybatis, which is mainly responsible for reading configuration files

5.2 SqlSessionFactoryBuilder

  1. This is mainly to create SqlSessionFactory objects

5.3 SqlSessionFactroy

  1. This is mainly to create SqlSession objects
  2. The program takes a long time to create this object and uses more resources. It's good to use one in the whole project
  3. This is an interface

5.4 openSession method

  1. No parameters: get the SqlSession object of the auto commit transaction
  2. With parameters
  • true: gets the SqlSession object of the auto commit transaction
  • false: get the SqlSession object of non auto commit transaction

5.5 SqlSession

  1. Is an interface that defines the method of operating data
  2. Use requirements
  • The SqlSession object is not thread safe and needs to be used inside the method. Before executing the sql statement, use openSession() to obtain it. After execution, it needs to be closed, so as to ensure that the thread is safe

06 working principle


  1. Mybatis-config.xml
    1. As the global configuration file of mybatis, the global configuration file of mybatis and the running environment of mybatis are configured.
  2. Mapper.xml
    1. SQL mapping file, in which the SQL language for operating the database is configured. This file needs to be in mybatis config XML
  3. Create a session factory through configuration information, SqlSessionFactory
  4. The session factory is used to create a session, that is, SqlSession
  5. The bottom layer of Mybatis customizes the operation database of the Executor interface. The Executor interface has two implementations
    1. Basic actuator
    2. Cache executor

07 SQL mapping file

Label 7.1

select, update, delete and insert correspond to query, modify, delete and add operations respectively

<insert id="save" parameterType="com.mybatis.model.Student">
  insert into student(username,sex,phone) values(#{username},#{sex},#{phone})
</insert>

<select id="getAllStudent" resultType="com.mybatis.model.Student">
  select * from student
</select>

<update id="update" parameterType="com.mybatis.model.Student">
  update student set phone=#{phone} where username=#{username}
</update>

<delete id="deleteByName" parameterType="java.lang.String">
  delete from student where username=#{username}
</delete>

7.2 parameterType

Specifies the type of the passed in parameter

7.2.1 basic data type

int findByAge(int age);
<select id="findByAge" parameterType="java.lang.Integer" resultType="java.lang.Integer">
  select count(*) from student where age= #{age}
</select>

7.2.2 String type

Delete student information according to user name

<delete id="deleteByName" parameterType="java.lang.String">
  delete from student where username=#{username}
</delete>

7.2.3 packaging

Add a piece of data to the student table

<insert id="save" parameterType="com.mybatis.model.Student">
  insert into student(username,sex,phone) values(#{username},#{sex},#{phone})
</insert>

7.2.4 multiple parameters

You can use param1 or age1 here. The number here indicates the number at which the method parameter is located

List<Student> findByNameAndPhone(String username,String phone);
<select id="findByNameAndPhone" resultType="com.mybatis.model.Student">
        select * from student where username=#{param1} and phone = #{param2}
    </select>

7.2.5 Map

#{key name}

 List<Student> findByNameAndPhone(Map map);
<select id="findByNameAndPhone" resultType="com.mybatis.model.Student">
        select * from student where username=#{username} and phone = #{phone}
    </select>

7.3 resultType

Result type

Java Bean

Result type and value. After SQL execution, the data will be converted to java objects
Default principle: assign a column name with the same name to an attribute with the same name

Treatment method

mybatis executes sql statements, and then calls the parameterless construction method of the class to create objects

mybatis pays the column value specified in the ResultSet to the property with the same name

Define alias

This must be defined in front of the label

    <typeAliases>
        <typeAlias type="Fully qualified name of custom type" alias="alias"></typeAlias>
    </typeAliases>

08 tools

public class MybatisUtils {
    private MybatisUtils(){}
    private static SqlSessionFactory sqlSessionFactory;
    static{
        String config = "mybatis-config.xml";
        try {
            InputStream in = Resources.getResourceAsStream(config);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static SqlSession getSession(){
        SqlSession sqlSession = null;
        if(sqlSessionFactory != null) {
            sqlSession = sqlSessionFactory.openSession();
        }
        return sqlSession;
    }
}

09 cascade operation

Use the < Association > and < Collection > sub tags in < resultmap > to perform association query

9.1 one to many

A department has multiple employees, and one employee can only be located in one department

Create entity class

@Data
public class Department {
    private Integer id;
    private String name;
    private List<Stuff> list;
}

@Data
public class Stuff {
    private long id;
    private String name;
    private Department department;
}

Create interface method

    List<Stuff> findInfo(long id);

Create SQL mapping file

<?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">
<mapper namespace="com.mybatis.dao.UserMapper">
    <resultMap id="StuffMap" type="com.mybatis.model.Stuff">
        <!--Map primary key-->
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <association property="department" javaType="com.mybatis.model.Department">
            <id column="did" property="id"></id>
            <result column="dname" property="name"></result>
        </association>
    </resultMap>
   
    <select id="findInfo" parameterType="java.lang.Long" resultMap="StuffMap">
        select s.id, s.name,d.name as dname,d.id as did
        from stuff s , department d
        where s.id = #{id} and s.did = d.id
    </select>
</mapper>

9.2 many to many

A customer can buy multiple products, and a product can be purchased by multiple users

Create entity class

@Data
public class Customer {
    private long id;
    private String name;
    private List<Goods> goods;
}
@Data
public class Goods {
    private long id;
    private String name;
    private List<Customer> customers;
}

Create Mapper interface

public interface ShoppingMapper {
    List<Customer> findById(long id);
}

create mapping file

<?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">
<mapper namespace="com.mybatis.dao.ShoppingMapper">
    <resultMap id="customer" type="com.mybatis.model.Customer">
        <id column="cid" property="id"></id>
        <result column="cname" property="name"></result>
        <collection property="goods" ofType="com.mybatis.model.Goods">
            <id column="gid" property="id"></id>
            <result column="gname" property="name"></result>
        </collection>
    </resultMap>
    <select id="findById" parameterType="long" resultMap="customer">
        select c.id as cid ,c.name as cname, g.id as gid , g.name as gname
        from customer c,goods g, cutomer_goods cg
        where c.id = #{id} and cg.cid = c.id and cg.gid = g.id
    </select>
</mapper>

10 compare between two placeholders

  1. #{}
    1. Relative safety
    2. The PreparedStatement object is used
    3. efficient
  2. ${}
    1. Easy Sql injection
    2. The Statement object is used
    3. Low efficiency

11 dynamic sql

The contents of sql statements are variable, and different sql statements can be obtained according to conditions

01 if

The if tag can decide whether to add the corresponding statement to SQL according to the value of the expression

<if test="judge java Object properties">
	part sql sentence
</if>

Example

    <select id="selectUniqueStudent" resultType="com.hl.mybatis.Student">
        select * from studentlist where
        1=1
        <if test="name!=''">
            and ID = #{ID}
        </if>>
    </select>

02 where

It is used for containing multiple if. When one of multiple if is established, a where keyword will be automatically added, and the redundant and and or in the if will be removed. Usually, if and where are used together

<select id="findGoodsByIdLazy" parameterType="com.mybatis.model.Goods" resultType="goods" >
    select * from goods
    <where>
        <if test="id != 0">
            id = #{id}
        </if>
        <if test="name != null">
            and username = #{name}
        </if>
    </where>
</select>

03 choose label

<select id="find" resultType="goods" parameterType="goods">
        select * from goods
        <where>
            <choose>
                <when test="id != 0">
                    id = #{id}
                </when>
                <when test="name != null">
                    name = #{name}
                </when>
            </choose>
        </where>
    </select>

04 trim

The prefix and suffix attributes in trim will be used to generate actual SQL statements and will be spliced with the statements inside the label. If prefixOverrides or the value specified in the suffix overrides attribute appear before and after the statement, Mybatis framework will automatically delete it

<trim prefix="where" prefixOverrides="and">
  <if test="id != 0">
    id = #{id}
  </if>
  <if test="username != null">
    and name = #{name}
  </if>
</trim>

05 set tag

For update operation, SQL statements will be automatically generated according to parameter selection

<update id="updateGoods">
  update goods 
  <set>
    <if test="name != null">
      name = #{name}
    </if>
  </set>
  where id = #{id}
</update>

06 foreach label

A series of values can be generated iteratively. This label is mainly used for in statements in SQL

<select id="find" resultType="goods">
    select * from goods
    <where>
        <foreach collection="ids" open="in in (" item="id" separator=",">
            #{id}
        </foreach>
    </where>
</select>

12 delayed loading

  1. What is deferred loading?
  • Delayed loading is also called lazy loading and lazy loading. The use of delayed loading can improve the operation efficiency of the program. For the operation of the data persistence layer, it can access a specific database under some specific circumstances and not access some tables under other circumstances, which reduces the interaction times of Java application in the database to a certain extent
  • When querying students and classes, students and classes are two different tables. If you only need to obtain students' information, you can query students' single label. If you need to obtain corresponding class information through students, you must query two tables
  • Different business requirements require different tables to be queried. According to specific business requirements, the work of data table query is to delay loading
  1. Development steps
  • In the main configuration file of Mybatis, enable deferred loading
<settings>
  <setting name="logImpl" value="STDOUT_LOGGING"/>
  <setting name="lazyLoadingEnabled" value="true"/>
</settings>
  • Split multi table Association query into multiple single table queries
<resultMap id="customer" type="com.mybatis.model.Customer">
    <id column="cid" property="id"></id>
    <result column="cname" property="name"></result>
    <association property="goods" javaType="com.mybatis.model.Goods" select="findGoodsByIdLazy" column="cid">

    </association>
</resultMap>
<select id="findCustomerByIdLazy" parameterType="long" resultMap="customer">
    select * from customer where id = #{id}
</select>
<select id="findGoodsByIdLazy" parameterType="long" resultType="goods" >
    select * from goods where id = #{id}
</select>

13 attribute profile of database

Put the connection information of the database in a separate file and separate it from the main configuration file of mybatis

Purpose: it is convenient to modify, save and process the information of multiple databases

Define an attribute configuration file in the resource directory, XXX properties

mybatis.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>
    <properties resource="jdbc.properties"></properties>
    <settings>
        <!--Set output log-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <typeAliases>
        <typeAlias type="java.lang.Integer" alias="i"></typeAlias>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.user}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com\hl\mybatis\StudentImpl.xml"/>
    </mappers>
</configuration>

jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/chat?serverTimezone=UTC
jdbc.user=root
jdbc.password=123456

14 specify multiple mapper files

Mode 1

<mappers>
  <mapper resource="com\hl\mybatis\StudentImpl.xml"/>
  <mapper resource="com\hl\mybatis\StudentImpl.xml"/>      
</mappers>

Mode 2

mapper file name should be consistent with dao interface name and case sensitive

The mapper file and dao interface need to be in the same directory

<mappers>
    
        <package name="mapper File location, fully qualified name"/>
    </mappers>

15 PageHelper

Mybatis general paging plug-in

Mode 1

Through sql

Through plug-ins

Join maven dependency

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.2.1</version>
</dependency>

Add dependency in mybatis main configuration file

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

Create test class

PageHelper. Startpage (number of starting pages, how many pieces of data are there on a page);

    @Test
    public void test8(){
        
        SqlSession sqlSession  = MybatisUtils.getSqlSession();
        
        PageHelper.startPage(1,3);
        
        List<Student> students = sqlSession.getMapper(StudentImpl.class).getAllStudent();
        
        System.out.println(students.size());
        
        for(Student s:students){
            
            System.out.println(s);
            
        }

    }

16 cache

Using cache can reduce the interaction times of Java application in the database, so as to improve the running efficiency of the program. For example, if an object with id = 1 is queried, the object will be automatically saved in the cache after the first query. In the next query, the object can be directly taken out of the cache without accessing the database again

01 L1 cache

The SqlSession level is enabled by default and cannot be closed

  1. When operating the database, you need to create a SqlSession object in which a HashMap is used to store cached data. The cached data areas do not affect each other between different sqlsessions.
  2. The scope of the first level cache is SqlSession. When the same SQL statement is executed twice in the same SqlSession, the results will be saved in the cache after the first execution, and the second query will be obtained directly from the buffer
  3. It should be noted that if SqlSession performs DML (insert, update, delete) operations, Mybatis must empty the cache to ensure the accuracy of data

02 L2 cache

Mapper level, which is off by default and can be turned on

2.1 basic information

  1. When using the L2 cache, multiple sqlsessions use the same Mapper SQL statement to operate the database, and the obtained data will be stored in the L2 cache. HashMap is also used for data storage. Compared with the L1 cache, the L2 cache has a larger range. Multiple sqlsessions can share the L2 cache, and the L2 cache is cross SqlSession
  2. The L2 cache is shared by multiple sqlsessions. Its scope is the same namespace of Mapper. Different sqlsessions execute SQL statements under the same namespace twice, and the parameters are also equal. After the first execution is successful, the data will be saved to the L2 cache, and the data will be taken out of the L2 cache between the second execution

2.2 Mybatis built-in L2 cache

  1. Mybatis master profile
<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
    <setting name="lazyLoadingEnabled" value="true"/>
    <setting name="cacheEnabled" value="true"/>
</settings>

  1. Mapper.xml file
<cache></cache>
  1. Entity classes implement serialization interfaces
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
    private String username;
    private String sex;
    private String phone;
    private Integer age;
    private Department department;
}

2.3 ehcache L2 cache

  1. Add dependency
 <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-ehcache</artifactId>
      <version>1.0.0</version>
    </dependency>
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache-core</artifactId>
      <version>2.0.0</version>
    </dependency>

  1. Add ehcache xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">     
    
    <diskStore path="java.io.tmpdir"/>         
    <defaultCache     
            maxElementsInMemory="10000"    
            eternal="false"    
            timeToIdleSeconds="120"    
            timeToLiveSeconds="120"    
            overflowToDisk="true"    
            maxElementsOnDisk="10000000"    
            diskPersistent="false"    
            diskExpiryThreadIntervalSeconds="120"    
            memoryStoreEvictionPolicy="LRU"    
            />     
</ehcache>
  1. Mybatis. Enable L2 cache in the main configuration file of XML
<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
    <setting name="lazyLoadingEnabled" value="true"/>
    <setting name="cacheEnabled" value="true"/>
</settings>
  1. Mapper. Configuring L2 cache in XML
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
  <!--After the cache is created, the time interval from the last access to the cache to the expiration of the cache-->
  <property name="timeToIdleSeconds" value="3600"/>
  <!--The interval between cache creation and expiration-->
  <property name="timeToLiveSeconds" value="3600"/>
  <!--Cache recycling policy-->
  <property name="memoryStoreEvictionPolicy" value="LRU"/>
</cache>
  1. Entity classes do not need to implement serialization interfaces

17 maven's filtering of static resources

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

Topics: Java Spring Back-end