Caching summary of mybatis

package com.atguigu.mybatis.test;

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;
import org.junit.Test;

import com.atguigu.mybatis.bean.Employee;
import com.atguigu.mybatis.dao.EmployeeMapper;

public class MyBatisTest {

	// Extract the method to obtain sqlSessionFactory

	public SqlSessionFactory getSqlSessionFactory() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		return new SqlSessionFactoryBuilder().build(inputStream);
	}

	/**
	 * Level 2 Cache: (Global Cache): Namespace-based Cache: A namespace corresponds to a Level 2 Cache: <br>
	 * Working mechanism: < br >
	 * 1,When a session queries a data, the data is placed in the first level cache of the current session; <br>
	 * 2,If the session is closed, the data in the first level cache will be saved in the second level cache, and the new session query information can refer to the content in the second level cache; <br>
	 * 3,sqlSession===EmployeeMapper==>Employee<br>
	 * DepartmentMapper===>Department<br>
	 * The data found by different namespace s will be placed in their corresponding cache (map) < br>.
	 * Effect: Data will be retrieved from the secondary cache < br >
	 * The data found will be placed in the first level cache by default. <br>
	 * Only after session submission or closure will the data in the first level cache be transferred to the second level cache < br >
	 * Use: <br>
	 * 1),Open the global secondary cache configuration: <set name="cacheEnabled" value="true"/><br>
	 * 2),Deploy secondary caching in mapper.xml: < br >
	 * <cache></cache><br>
	 * 3),Our POJO needs to implement a serialized interface <br>.
	 * 
	 * 
	 * Cache-related settings/attributes: <br>
	 * 1),cacheEnabled=true: false: Close Cache (Level 2 Cache Close) (Level 1 Cache Always Available) <br>
	 * 2),Each select tag has useCache="true": <br>
	 * false: No caching (primary caching is still used, secondary caching is not used)<br>
	 * 3),[Every tag added or deleted: flushCache="true": <br>
	 * After the execution of add, delete and change, the cache will be clear; < br >
	 * Test: flushCache="true": The first level cache will be emptied; the second level will also be cleared; <br>
	 * Query tag: flushCache="false": <br>
	 * If flushCache=true; the cache is emptied after each query; the cache is not used; <br>
	 * 4),sqlSession.clearCache();Only the first level cache of the current session is clear; < br >
	 * 5),localCacheScope: Local cache scope: (first-level cache SESSION); all data of current session is stored in session cache; <br>
	 * STATEMENT: First-level caching can be disabled; < br >
	 * 
	 * @throws IOException
	 * <br>
	 * <br>
	 * 
	 *             Third Party Cache Integration: <br>
	 *             1),Import third-party caching packages; < br >
	 *             2),Import adapter packages integrated with third-party caches; officially available; <br>
	 *             3),mapper.xml Use custom caching < br >
	 *             <cache type="org.mybatis.caches.ehcache.EhcacheCache"><br>
	 */
	@Test
	public void testSecondLevelCache() throws IOException {
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		SqlSession openSession2 = sqlSessionFactory.openSession();
		try {
			// 1,
			EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
			EmployeeMapper mapper2 = openSession2.getMapper(EmployeeMapper.class);

			Employee emp01 = mapper.getEmployeeById(1);
			System.out.println(emp01);
			openSession.close();

			// The second query is the data from the secondary cache, and no new sql is sent.
			// mapper2.addEmp(new Employee(null, "aaa", "nnn", "0"));
			Employee emp02 = mapper2.getEmployeeById(1);
			System.out.println(emp02);
			openSession2.close();

		} finally {

		}
	}

	/**
	 * Level 1 cache: (local cache): sqlSession level cache. The first level cache is always open; a Map < br > at the SqlSession level
	 * The data queried during the same session with the database is placed in the local cache. <br>
	 * If you need to get the same data in the future, take it directly from the cache, there is no need to query the database again; < br >
	 * 
	 * First-level cache invalidation (if the current first-level cache is not used, the effect is that queries need to be sent to the database again): <br>
	 * 1,sqlSession Different. <br>
	 * 2,sqlSession The same, the query conditions are different. (There is no such data in the current first level cache)<br>
	 * 3,sqlSession Similarly, an addition or deletion operation was performed between the two queries (this addition or deletion may have an impact on the current data)<br>
	 * 
	 * @throws IOException
	 * <br>
	 */
	/*Test Level 1 Cache*/
	@Test
	public void testCache() throws IOException {
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		try {
			EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
			Employee emp01 = mapper.getEmployeeById(1);
			System.out.println(emp01);

			// xxxxx
			// 1. sqlSession is different.
			// SqlSession openSession2 = sqlSessionFactory.openSession();
			// EmployeeMapper mapper2 = openSession2.getMapper(EmployeeMapper.class);

			// 2. The same sqlSession and different query conditions

			// 3. The sqlSession is the same. Additions and deletions are performed between the two queries (this addition and deletion may have an impact on the current data).
			// mapper.addEmp(new Employee(null, "testCache", "cache", "1"));
			// System.out.println("Data Added Successfully");

			// 4. The sqlSession is the same. The first level cache is cleared manually (the cache is empty)
			// openSession.clearCache();

			Employee emp02 = mapper.getEmployeeById(1);
			// Employee emp03 = mapper.getEmpById(3);
			System.out.println(emp02);
			// System.out.println(emp03);
			System.out.println(emp01 == emp02);

			// openSession2.close();

		} finally {
			openSession.close();
		}
	}

}


Configuration of corresponding mapping files

    <cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
	<!--  
	eviction: Cache recovery strategy:
		LRU - The least recently used: Remove objects that have not been used for the longest time.
		FIFO - First in, first out: Remove objects in the order they enter the cache.
		SOFT - Soft Reference: Remove objects based on garbage collector status and soft reference rules.
		WEAK - Weak Reference: More actively remove objects based on garbage collector state and weak reference rules.
		* The default is LRU.
	Flush Interval: Cache refresh interval
		How often does the cache empty? The default is not clear. Set a value in milliseconds.
	readOnly: Read Only:
		true: read-only; mybatis believes that all operations to retrieve data from the cache are read-only and do not modify the data.
				 In order to speed up the acquisition, mybatis will directly refer the data in the cache to the user. Insecurity, speed
		false: not read-only: mybatis feels that the acquired data may be modified.
				mybatis will clone a new data for you using serialization-deserialization technology. Safety, Slow Speed
	size: How many elements are stored in the cache?
	type=": Specifies the full class name of the custom cache;
			Implement the Cache interface.
	-->
 	<!-- <cache ></cache>   -->
	<! - Use third-party caching - >
	 
	
	<!--public Map<Integer, Employee> getEmpByLastNameLikeReturnMap(String lastName);  -->
 	<select id="getEmpByLastNameLikeReturnMap" resultType="com.atguigu.mybatis.bean.Employee">
 		select * from tbl_employee where last_name like #{lastName}
 	</select>
	<! -- Returns the list of elements in the resu lt type that need to be written in the collection - >
		<!-- public List<Employee> getEmpsByLastNameLike(String lastName); -->
	<select id="getEmpsByLastNameLike" resultType="emp" databaseId="mysql">
		select * from tbl_employee where last_name like #{lastName}
	</select>
	<! - The return value is a key in a map map: the database field name value: the field value - >.
	<!-- public Map<String, Object> getEmpByIdReturnMap(Integer id); -->
	<select id="getEmpByIdReturnMap" resultType="map">
		select * from tbl_employee where id =#{id}
	</select>	
	
	<! - The following database ID corresponds to the alias of the database manufacturer that I started earlier, so that we can dynamically switch data - >.
	<select id="getEmployeeById" resultType="emp" databaseId="mysql">
		select * from tbl_employee where id = #{id}
	</select>
	
	<! - Testing the values of mu lt iple parameters - >
	<!-- public Employee getEmpByIdandLastname(Integer id, String lastName); -->
	
	<select id="getEmpByIdandLastname" resultType="emp">

		select * from tbl_employee where id = #{id} and last_name=#{lastName}
	</select> 
	
	<!-- public Employee getEmpByMap(Map<String, Object> map); -->
	
	<select id="getEmpByMap" resultType="emp">
		select * from tbl_employee where id =#{id} and last_name =#{lastName}
	</select>

Keywords: Session Mybatis Database Apache

Added by yogadt on Tue, 04 Jun 2019 23:01:33 +0300