Level 1 cache and Level 2 cache in Mybatis

Table of contents

1. What is cache?

Second, what is the first level cache?

1.JavaBean class:

2.Dao layer:

3.mapper layer:

4.view layer:

3. What is the second level cache?

1. Steps for opening the second level cache in Mybatis:

1.1 Open in xml

1.2 Open in annotations

Fourth, the difference between the first level cache and the second level cache

1. What is cache?

Cache (cache), a buffer for data exchange, when an application needs to read data, it first takes out the data from the database and places it in the buffer, and the application reads the data from the buffer.

Features of Cache: The data retrieved from the database is stored in memory, enabling fast reading and use.
Cache limitation: No need to get from the database when reading, the data may not be the latest.

Second, what is the first level cache?

The first-level cache is also called the SqlSession-level cache, which can be used directly without manual activation. The cache space is allocated separately for each SqlSession, and the caches between multiple SqlSessions are not shared.

An example of the first level cache is as follows:

1.JavaBean class:

package com.ape.bean;

import java.util.Date;

public class Student {
	private String sid;
	private String sname;
	private Date birthday;
	private String ssex;
	private int classid;
	public String getSid() {
		return sid;
	}
	public void setSid(String sid) {
		this.sid = sid;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getSsex() {
		return ssex;
	}
	public void setSsex(String ssex) {
		this.ssex = ssex;
	}
	public int getClassid() {
		return classid;
	}
	public void setClassid(int classid) {
		this.classid = classid;
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Student(String sid, String sname, Date birthday, String ssex, int classid) {
		super();
		this.sid = sid;
		this.sname = sname;
		this.birthday = birthday;
		this.ssex = ssex;
		this.classid = classid;
	}
	@Override
	public String toString() {
		return "Student [sid=" + sid + ", sname=" + sname + ", birthday=" + birthday + ", ssex=" + ssex + ", classid="
				+ classid + "]";
	}
	
}

2.Dao layer:

package com.ape.dao;

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 DaoUtil {
	
	private static SqlSessionFactory build;
	
	static {
		
		try {
			InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
		
			build = new SqlSessionFactoryBuilder().build(resourceAsStream);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static SqlSession getSqlSession() {
		return build.openSession();
	}
	
	public static void closeResource(SqlSession sqlSession) {
		sqlSession.close();
	}
	
	
	
	
	

}

3.mapper layer:

package com.ape.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Select;

import com.ape.bean.Student;

public interface IStudentMapper {
	//Query the data in the student table by sid
	@Select("select * from student where sid = #{sid}")
	List<Student> findStudentBySid(int sid);
	
	
	//Delete data in student table by sid
	@Delete("delete from student where sid = #{sid}")
	int deleteStudentBySid(int sid);
}

4.view layer:

package com.ape.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.ape.bean.Student;
import com.ape.dao.DaoUtil;
import com.ape.mapper.IStudentMapper;

public class Test1 {
	public static void main(String[] args) {
		SqlSession sql = DaoUtil.getSqlSession();
		IStudentMapper mapper = sql.getMapper(IStudentMapper.class);
		
		//The first time to query the corresponding data by sid
		List<Student> findStudentBySid1 = mapper.findStudentBySid(1);
		System.out.println(findStudentBySid1);
		
		
		System.out.println("----------------------------------------------------------");
		
		
		//The second time to query the corresponding data through sid
		List<Student> findStudentBySid2 = mapper.findStudentBySid(1);
		System.out.println(findStudentBySid2);
		
		
		//release resources
		sql.close();
		
		
	}
}

operation result:

Under what circumstances will the L1 cache be invalidated?
1. Not using the same SqlSession

package com.ape.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.ape.bean.Student;
import com.ape.dao.DaoUtil;
import com.ape.mapper.IStudentMapper;

public class Test1 {
	public static void main(String[] args) {
		//first SqlSession
		SqlSession sql1 = DaoUtil.getSqlSession();
		IStudentMapper mapper1 = sql1.getMapper(IStudentMapper.class);
		
		List<Student> findStudentBySid1 = mapper1.findStudentBySid(1);
		System.out.println(findStudentBySid1);
		
		
		System.out.println("-----------------------------------------------------------------------------------------------------");
		
		
		//Second SqlSession
		SqlSession sql2 = DaoUtil.getSqlSession();
		IStudentMapper mapper2 = sql2.getMapper(IStudentMapper.class);
		
		List<Student> findStudentBySid2 = mapper2.findStudentBySid(1);
		System.out.println(findStudentBySid2);
		
		//release resources
		sql1.close();
		sql2.close();
		
		
	}
}


2. The single query conditions of the same SqlSession are different

package com.ape.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.ape.bean.Student;
import com.ape.dao.DaoUtil;
import com.ape.mapper.IStudentMapper;

public class Test1 {
	public static void main(String[] args) {
		SqlSession sql = DaoUtil.getSqlSession();
		IStudentMapper mapper = sql.getMapper(IStudentMapper.class);

		//The first single query condition sid=1
		List<Student> findStudentBySid1 = mapper.findStudentBySid(1);
		System.out.println(findStudentBySid1);


		System.out.println("----------------------------------------------------------");


		//The second single query condition sid=2
		List<Student> findStudentBySid2 = mapper.findStudentBySid(2);
		System.out.println(findStudentBySid2);


		//release resources
		sql.close();


	}
}


3. Additions, deletions and changes have been made to the same SqlSession

package com.ape.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.ape.bean.Student;
import com.ape.dao.DaoUtil;
import com.ape.mapper.IStudentMapper;

public class Test1 {
	public static void main(String[] args) {
		SqlSession sql = DaoUtil.getSqlSession();
		IStudentMapper mapper = sql.getMapper(IStudentMapper.class);
		
		//The first time to query the corresponding data by sid
		List<Student> findStudentBySid1 = mapper.findStudentBySid(1);
		System.out.println(findStudentBySid1);
		
		//Do a delete operation by sid
		int a = mapper.deleteStudentBySid(2);
		if (a > 0) {
			sql.commit();
			System.out.println("successfully deleted!");
		}else {
			sql.rollback();
			System.out.println("failed to delete!");
		}
		
		System.out.println("----------------------------------------------------------");
		
		
		//The second time to query the corresponding data through sid
		List<Student> findStudentBySid2 = mapper.findStudentBySid(1);
		System.out.println(findStudentBySid2);
		
		
		//release resources
		sql.close();
		
		
	}
}


4. Actively emptied the cache()

package com.ape.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.ape.bean.Student;
import com.ape.dao.DaoUtil;
import com.ape.mapper.IStudentMapper;

public class Test1 {
	public static void main(String[] args) {
		SqlSession sql = DaoUtil.getSqlSession();
		IStudentMapper mapper = sql.getMapper(IStudentMapper.class);
		
		//The first time to query the corresponding data by sid
		List<Student> findStudentBySid1 = mapper.findStudentBySid(1);
		System.out.println(findStudentBySid1);
		
		//Actively clear the cache
		sql.clearCache();
		
		System.out.println("----------------------------------------------------------");
		
		
		//The second time to query the corresponding data through sid
		List<Student> findStudentBySid2 = mapper.findStudentBySid(1);
		System.out.println(findStudentBySid2);
		
		
		//release resources
		sql.close();
		
		
	}
}

 

3. What is the second level cache?

It is another cache mechanism of mybatis. It is different from the first-level cache. It is at the namespace level, that is, one mapper and one cache, which are independent of each other and do not affect each other. Multiple sqlSession s under the same namespace can share the cache. It is not enabled by default and needs to be configured. on.

1. Steps for opening the second level cache in Mybatis:

1.1 Open in xml

(1) Configure in sqlMapConfig.xml of mybatis:

                                        

(2) Configure in sqlmap of mybatis (configured in mapper.xml):

(3) Configure in the operation used (for example, in the select tag)

1.2 Open in annotations

(1) Configure in sqlMapConfig.xml of mybatis

(2) Use @CacheNamespace directly on the interface definition and set blocking to true

L2 cache summary:

1. Compared with the first-level cache, the second-level cache of Mybatis realizes the sharing of cached data and is more controllable.
2. It is very likely that wrong data will appear, there are design defects, and the conditions for safe use are harsh.
3. In a distributed environment, wrong data will inevitably be read, so it is not recommended to use it, just understand.

Fourth, the difference between the first level cache and the second level cache

1. The first level cache is at the SqlSession level and the second level cache is at the SqlSessionFactory level
2. The first level cache is written to the memory and the second level cache is directly serialized and written to the disk
3. The first-level cache is automatically opened, and the second-level cache needs to be opened manually

Tags: Cache

Posted by ohaus on Mon, 19 Sep 2022 02:17:58 +0930