This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

1. Mybatis loading strategy

1.1. What is lazy loading

Lazy loading: loading data only when it is needed and not when it is not needed. Lazy loading is also called lazy loading.

1.1.1. Advantages of lazy loading

Query from a single table first, and then associate the query from the associated table if necessary. This greatly improves database performance because it is faster to query a single table than to associate the query with multiple tables

1.1.2 disadvantages of lazy loading

Because only when the data is needed, the database query will be carried out, so in the case of large volume data query, because the query work also consumes time, it may cause users to wait for a long time, resulting in a decline in user experience.

1.1.3 matters needing attention

  • In multi-tables, one-to-many, many-to-many: lazy loading is usually used, one-to-one (many-to-one): immediate loading is usually used

  • Lazy loading is implemented based on nested queries

1.2. Implementation of lazy loading

1.2.1. Partial lazy loading

There is a fetchType attribute in both the Association and Collection tags, and you can modify the local load policy by changing its value.

<! -- Enable one-to-many lazy loading -->
<resultMap id="userMap" type="user">
<id column="id" property="id"></id>
    <result column="username" property="username"></result>
    <result column="password" property="password"></result>
    <result column="birthday" property="birthday"></result>
<! FetchType ="eager" -->

    <collection property="orderList" ofType="order" column="id"
                select="com.111.dao.OrderMapper.findByUid" fetchType="lazy">
    </collection>
</resultMap>
<select id="findAll" resultMap="userMap">
    SELECT * FROM `user`
</select>
Copy the code

1.2.2. Set the method of triggering lazy loading

Override the equals, Clone, hashCode, and toString methods of the current object using the lazyLoadTriggerMethods configuration item in the configuration file

<settings>
<! -- Enable global lazy loading -->
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
Copy the code

1.2.3. Global lazy loading

The global loading policy can be modified using the setting tag in the core configuration file of Mybatis.

<settings>

<! -- Enable global lazy loading -->

<setting name="lazyLoadingEnabled" value="true"/>

</settings>
Copy the code

Note:

A local load policy takes precedence over a global load policy.

1.3. Mybatis Cache

1.3.1. The role of cache

Frequently query some data that does not change frequently, use cache to improve query efficiency, and use cache strategy to reduce the number of database queries to improve performance.

1.3.2 Level 1 Cache

1.3.2.1 Overview of Level 1 Cache

Level 1 cache is SqlSession level cache and is enabled by default

So in the case that the parameters and SQL are exactly the same, we use the same SqlSession object to call a Mapper method, usually only execute SQL once, because after using SelSession for the first time query, MyBatis will put it in the cache, later query, if there is no declaration to refresh, If the cache does not time out, THE SqlSession will fetch the current cached data instead of sending the SQL to the database again.

1.3.2.2 Verify level 1 cache

@Test

public void testOneCache(a) throws Exception {

    SqlSession sqlSession = MyBatisUtils.openSession();

    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

User user1 = userMapper.findById(1); System.out.println("First query user :" + user1);

User user2 = userMapper.findById(1); System.out.println("Second query user :" + user2);

    sqlSession.close();

}
Copy the code

1.3.2.3 Analysis of level 1 cache

Level 1 cache is the CACHE of the SqlSession scope. The cache will be cleared by executing the C(add)U(update)D(delete) operation of the SqlSession or calling the clearCache(), COMMIT (), and close() methods.

Explanation:

  1. When you query information about the user whose ID is 41 for the first time, check whether there is information about the user whose ID is 41 in the cache. If there is no information about the user, query the user information from the database.

  2. Get the user information and store the user information in the level 1 cache.

  3. If sqlSession goes to commit (perform insert, update, delete), clear level 1 cache in sqlSession, this

The purpose of this exercise is to keep the latest information stored in the cache and avoid dirty reads.

  1. On the second attempt to query information about the user whose ID is 41, check whether there is information about the user whose ID is 41 in the cache. The user information is directly obtained from the cache.

1.3.2.4. Clear level 1 cache

@Test

public void testClearOneCache(a) throws Exception {

SqlSession sqlSession = MybatisUtils.openSession();

UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user1 = userMapper.findById(41); System.out.println("First query user :" + user1);

Sqlsession.clearcache (); sqlsession.clearCache ();

    User user2 = userMapper.findById(41);

System.out.println("Second query user :" + user2); }
Copy the code
<! Caches are cleared each time a query is made

< select flushCache="true"></select>
Copy the code

1.3.3 Level 2 Cache

1.3.3.1 Overview of Level 2 Caching

Level 2 caching is namspace level (across sqlSession) caching and is disabled by default

To enable level 2 caching, MyBatis requires that poJOs returned must be serializable. The Serializable interface can be easily configured to enable level 2 caching in a mapping XML file.

1.3.3.2, validation,

  • Configure the core profile
<settings>

<! Since cacheEnabled is set to true by default, this step can be omitted. If the value is true, level 2 cache is enabled. False indicates that level-2 caching is disabled. -->

    <setting name="cacheEnabled" value="true"/>

</settings>
Copy the code
  • Configure the usermapper. XML mapping
<mapper namespace="com.111.dao.UserMapper">
<! -- Enable level 2 cache for current mapping files --> 
<cache></cache>

<! Set useCache= "true" in the <select> tag to indicate that the current statement uses level 2 caching. Note: Use useCache="false" to disable level 2 caching when the latest data SQL is required for each query. -->
<select id="findById" parameterType="int" resultType="user" useCache="true">
        SELECT * FROM `user` where id = #{id}
    </select>
</mapper>
Copy the code
  • Modify the User entity class

public class User implements Serializable {
    private Integer id;
    private String username;

    private Date birthday;

    private String sex;

    private String address;

    private List<Role> roleList;

    private List<Order> orderList;

}
Copy the code
  • The test results
@Test

public void testTwoCache(a) throws Exception {

    SqlSession sqlSession = MyBatisUtils.openSession();

    UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.findById(41); System.out.println("First query user :" + user); sqlSession.close();

    SqlSession sqlSession1 = MyBatisUtils.openSession();

    UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class); User user1 = userMapper1.findById(41); System.out.println("Second query user :"+user1);

    sqlSession1.close();
}
Copy the code

1.3.3.3 Analysis of level 2 Cache

Level-2 cache is the cache of mapper mapping level. Multiple SQLsessions can operate the SQL statement of the same MAPper mapping. Multiple SQLsessions can share level-2 cache, and level-2 cache is cross-SQLSession.

1. All select statements in the mapping statement file will be cached. 2. All INSERT, UPDATE, and DELETE statements in the mapping statement file flush the cache.Copy the code

1.3.3.4 Matters needing attention

Mybatis level 2 cache is namespace level, so it can cause dirty read problems when performing multiple table queries

1.3.4,

  1. Mybatis cache, we do not need to manually store and obtain data. Mybatis is automatically maintained.

  2. Mybatis enabled level 2 cache, then query order: Level 2 cache — “level 1 cache –” database

  3. Note: Mybatis level 2 cache will have a dirty read problem, need to use a third party caching technology to solve the problem.

2, Mybatis common annotations

* @Insert<insert></insert> *@Delete: Implements the delete instead of <delete></delete> *@Update: Implements updates instead of <update></update> *@Select: implements the query instead of <select></select> *@Result: implements result set encapsulation instead of <result></result> *@ResultsAnd:@ResultWhen used together, multiple result sets are encapsulated instead of <resultMap></resultMap> *@One: implements one-to-one result set encapsulation instead of <association></association> *@Many: Implement one-to-many result set encapsulation instead of <collection></collection>Copy the code

Annotation lazy loading

* fetchType = fetchType.LAZY indicates LAZY loading. * fetchType = fetchTypeCopy the code