1, the introduction of
What is MyBatis:
MyBatis is an open source project of Apache called iBatis. In 2010, this project was migrated to Google Code by Apache Software Foundation and renamed as MyBatis. Migrated to Github in November 2013.
MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all of the JDBC code and the work of setting parameters and fetching result sets. MyBatis can configure and map primitive types, interfaces, and Java POJOs (Plain Old Java Objects) to records in the database via simple XML or annotations.
Maven repositories:
<! -- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> < artifactId > mybatis < / artifactId > < version > 3.5.6 < / version > < / dependency >Copy the code
2. Basic configuration
2.1. Import dependencies
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <! -- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> < artifactId > mysql connector - Java < / artifactId > < version > 5.1.49 < / version > < / dependency > <! -- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>Copy the code
2.2. Core configuration files
<? The 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 Configuration file --> <configuration> <environments default="development"> <environment ID ="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" Value = "JDBC: mysql: / / 192.168.1.101:3306 / mybatis? useSSL=true& useUnicode=true& characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <! -- each Mapper. XML needs to be registered in Mbatis core configuration file - > < mappers > < Mapper resource = "com/Luke/dao/UserMapper. XML" / > < / mappers > </configuration>Copy the code
3, add, delete, change and check
3.1. UserMapper interface
public interface UserMapper { List<User> getUser(); User getUserById(int id); Int addUser(User User); // Add User int updateUser(User User); Int deleteUserById(int id); // Delete user}Copy the code
3.2, UserMappper. XML
<? The 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.luke.dao.UserMapper"> <select id="getUser" resultType="com.luke.pojo.User"> select * from user; </select> <select id="getUserById" resultType="com.luke.pojo.User" parameterType="int"> select * from user where id = #{id}; </select> <insert id="addUser" parameterType="com.luke.pojo.User"> insert into user (id,name,pwd) values (#{id},#{name},#{pwd}); </insert> <update id="updateUser" parameterType="com.luke.pojo.User"> update user set name = #{name},pwd = #{pwd} where id = #{id}; </update> <delete id="deleteUserById" parameterType="int"> delete from user where id = #{id}; </delete> </mapper>Copy the code
3.3. Util Utility class
public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { String resource = "mybatis-config.xml"; InputStream inputStream; inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); }}Copy the code
3.4. Test classes
Public class MyTest {// Query all users @test public void testGetUser(){SqlSession SqlSession = null; try { sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.getUser(); for (User user : users) { System.out.println(user.toString()); } } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession ! = null) sqlSession.close(); }} @test public void testGetUserById(){SqlSession SqlSession = null; try { sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession ! = null) sqlSession.close(); @test public void testInsert(){SqlSession SqlSession = null; sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Int I = mapper.addUser(new User(4," shuai ","123456")); System.out.println(i); sqlSession.commit(); Sqlsession.close (); @test public void testUpdate(){SqlSession SqlSession = null; sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Int I = mapper.updateUser(new User(4," 1234567")); System.out.println(i); sqlSession.commit(); Sqlsession.close (); @test public void testDelete(){SqlSession SqlSession = null; sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int i = mapper.deleteUserById(4); System.out.println(i); sqlSession.commit(); Sqlsession.close (); }}Copy the code
3.5. Use Map as an input parameter
Map passes the parameter, fetching the key directly from SQL.
4. Configuration resolution
The common name is mybatis-config.xml
The MyBatis configuration file contains Settings and property information that will deeply affect MyBatis behavior.
4.1 Environment Configuration
MyBatis can be configured to adapt to multiple environments, distinguished by environment ID.
Keep in mind, though: although multiple environments can be configured, only one environment can be selected per SqlSessionFactory instance.
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
Copy the code
Mybatis default transaction manager is: JDBC connection pool: POOLED
4.2 Properties
Configuration files can be referenced through the properties property
These properties can be configured externally and can be dynamically replaced. You can configure these properties either in a typical Java properties file or in a child element of the Properties element.
db.properties
. Driver = com. Mysql. JDBC driver url = JDBC: mysql: / / 192.168.1.101:3306 / mybatis? useSSL=false&characterEncoding=UTF-8 username=root password=rootCopy the code
Core configuration file introduction:
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="123456"/>
</properties>
Copy the code
- You can import external files directly,
- You can add some attributes to it
- If the same field is added to the external file and property, the external file is preferred
4.3 typeAliases
A type alias sets an abbreviated name for a Java type. It is only used for XML configuration and is intended to reduce redundant fully qualified class name writing.
<typeAliases>
<typeAlias type="com.luke.pojo.User" alias="user"/>
</typeAliases>
Copy the code
When configured this way, user can be used anywhere com.luke. Pojo.user is used.
<typeAliases>
<package name="com.luke.pojo"/>
</typeAliases>
Copy the code
You can also specify a package name. MyBatis will search for the desired Java Bean under the package name and, in the absence of annotations, use the Bean’s lowercase, unqualified class name as its alias.
You can also add aliases using annotations
@Alias("user")
public class User {
private int id;
private String name;
private String pwd;
}
Copy the code
4.4 Settings
These are very important tuning Settings in MyBatis, and they change the runtime behavior of MyBatis.
-
CacheEnabled: Globally enables or disables any caches that have been configured in all mapper profiles.
-
LazyLoadingEnabled: global switch of lazy loading.
-
MultipleResultSetsEnabled: whether to allow more than a single statement returns a result set
-
UseColumnLabel: Uses column labels instead of column names. The actual performance is database driven.
-
UseGeneratedKeys: Allows JDBC support for automatic primary key generation, which requires database driver support.
-
AutoMappingBehavior: Specifies how MyBatis should automatically map columns to fields or properties.
-
NONE indicates that automatic mapping is disabled.
-
PARTIAL only automatically maps fields that do not define nested result mappings.
-
FULL automatically maps any complex result set (whether nested or not).
-
AutoMappingUnknownColumnBehavior: specify found automatically map the target unknown column (or unknown attribute types).
-
NONE: Does nothing
-
WARNING: the output WARNING logs (‘ org. Apache. Ibatis. Session. AutoMappingUnknownColumnBehavior ‘log level should be set to WARN)
-
FAILING: mapping failure (throwing SqlSessionException)
-
DefaultExecutorType: Configures the default executor.
-
SIMPLE is a plain actuator;
-
The REUSE executor reuses preparedStatements.
-
The BATCH executor not only reuses statements but also performs BATCH updates.
-
DefaultStatementTimeout: Sets the timeout time, which determines the number of seconds the database driver waits for a database response.
-
DefaultFetchSize: Sets a recommended value for the driver’s result set fetchSize. This parameter can only be overridden in query Settings.
-
SafeRowBoundsEnabled: Whether paging is allowed in nested statements (RowBounds). Set to false if allowed.
-
MapUnderscoreToCamelCase: indicates whether to enable automatic mapping of camel name, that is, from the classic database column name A_COLUMN to the classic Java property name aColumn.
-
LocalCacheScope: MyBatis uses Local caching to prevent circular references and speed up repeated nested queries.
-
The default value is SESSION, which caches all queries executed in a SESSION.
-
If the value is set to STATEMENT, the local cache will only be used to execute statements. Different queries of the same SqlSession will not be cached.
-
JdbcTypeForNull: The default JDBC type for null values when no specific JDBC type is specified for the parameter.
-
LazyLoadTriggerMethods: Specifies which methods of an object trigger a lazy load.
-
LogImpl: Specifies the specific implementation of logging used by MyBatis. If not specified, it will be found automatically.
4.5 Other Configurations
typeHandlers
When MyBatis sets a parameter in a PreparedStatement or fetches a value from a result set, it uses a type handler to convert the obtained value to a Java type in an appropriate manner.
objectFactory
Each time MyBatis creates a new instance of the resulting object, it uses an ObjectFactory instance to complete the instantiation.
Plugins
- mybatis-generator-core
- mybatis-plus
- General mapper
4.6 mappers
Tell MyBatis where to find the SQL statement.
-
Use resource references relative to the classpath
-
Using fully qualified resource locators (urls)
-
Implement the fully qualified class name of the class using the mapper interface
Note: The interface and its Mapper configuration file must have the same name and be in the same package.
-
Register all mapper interface implementations within the package as mappers
Note: The interface and its Mapper configuration file must have the same name and be in the same package.
Scope and life cycle
- SqlSessionFactoryBuilder
The best scope for SqlSessionFactoryBuilder instances is the method scope (that is, local method variables).
- SqlSessionFactory
Once created, the SqlSessionFactory should persist for the duration of the application, and there is no reason to discard it or recreate another instance.
The best scope for SqlSessionFactory is the application scope.
There are many ways to do this, the easiest is to use singleton or static singleton.
- SqlSession
Each thread should have its own INSTANCE of SqlSession. An instance of SqlSession is not thread-safe and therefore cannot be shared, so its best scope is the request or method scope.
It needs to be turned off when it’s done.
5, solve the problem of inconsistent attribute name and field name: ResultMapper
The resultMap element is the most important and powerful element in MyBatis.
ResultMapper Result mapping:
<resultMap id="UserMap" type="user"> <result column="id" property="id"/> <result column="name" property="name"/> <result column="pwd" property="password"/> </resultMap> <select id="getUser" resultMap="UserMap"> select * from user; </select>Copy the code
6, logs,
6.1 Log Factory
When an exception occurs in the database, log help is required.
Mybatis provides logging functionality by using a built-in log factory. The built-in logging factory will delegate logging to one of the following implementations:
- SLF4J,
- LOG4J, 【 用】
- LOG4J2,
- JDK_LOGGING,
- COMMONS_LOGGING,
- STDOUT_LOGGING
- NO_LOGGING
Which one you want to use is specified in the Settings
<settings> <! <setting name="logImpl" value="STDOUT_LOGGING"/></ Settings >Copy the code
6.2, LOG4J
Log4j’s brief introduction:
- Log4j is an open source project of Apache. Using Log4j, you can control the destination of log messages to the console, files, GUI components, even the socket server, NT event loggers, UNIX Syslog daemons, and so on
- We can also control the output format of each log
- By defining the level of each log message, we can more carefully control the log generation process
- These can be configured flexibly through a configuration file without the need to modify the application code
Import dependence
<! -- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> < artifactId > log4j < / artifactId > < version > 1.2.17 < / version > < / dependency >Copy the code
Configuration file: log4j.properties
Output DEBUG logs to the console and file destinations Log4j.appender. console = log4j.appender.console = log4j.appender.console = 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 # file output associated Settings log4j. Appender. The file = org.. Apache log4j. RollingFileAppender log4j. Appender. File. The file =. / log/Luke. 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] [% d {yy - MM - dd}] [c] % % m % n # log4j.logger.org.mybatis=DEBUG log output level log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUGCopy the code
configuration
<settings>
<setting name="logImpl" value="LOG4J"/></settings>
Copy the code
When used in Java:
static Logger logger = Logger.getLogger(MyTest.class); @test public void testLog4j(){logger.info("info: enter testLog4j"); Logger. debug("debug: entered testLog4j"); Logger. error("error: entered testLog4j"); }Copy the code
7, paging
Function:
- Reduce the amount of data processed
7.1. Use Limit paging
select * from user limit startIndex,pageSize;
Copy the code
Implemented using Mybatis
Interface:
List<User> getUserByLimit(Map<String,Object> map);
Copy the code
sql:
<select id="getUserByLimit" resultMap="UserMap" parameterType="map">
select * from user limit #{startIndex},#{pageSize}
</select>
Copy the code
The test class:
@Test public void getUserByLimit(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("startIndex",1); map.put("pageSize",2); List<User> userList = mapper.getUserByLimit(map); for (User user : userList) { System.out.println(user); }}Copy the code
7.2, RowBounds
interface
List<User> getUserByRowBounds();
Copy the code
sql:
<select id="getUserByRowBounds" resultMap="UserMap" >
select * from user;
</select>
Copy the code
The test class
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
RowBounds rowBounds = new RowBounds(2,2);
List<User> userList = sqlSession.selectList("com.luke.dao.UserMapper.getUserByRowBounds", null, rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
Copy the code
8. Use annotations
8.1 Interface oriented programming
-
You’ve all learned about object-oriented programming before, you’ve learned about interfaces, but in real development, a lot of times we’ll choose interface oriented programming
-
Root cause: Decoupling, extensibility, improved reuse, layered development, the top layer does not care about the specific implementation, everyone follows the common standards, making development easier and more standardized
-
In an object-oriented system, the various functions of the system are performed by many different objects. In this case, how each object implements itself internally is less important to the system designer;
-
And the cooperative relationship between each object becomes the key of system design. Small to the communication between different classes, to the interaction between each module, at the beginning of the system design are to be considered, which is also the main content of the system design. Interface oriented programming means programming with this in mind.
Understanding of interfaces
-
Interfaces, at a deeper level, should be understood as the separation of definition (specification, constraint) from implementation (principle of separation of name and reality).
-
The interface itself reflects the abstract understanding of the system designer.
-
Interfaces should have two types:
-
The first type is the abstraction of an individual, which can correspond to an abstract class.
-
The second type is the abstraction of a certain aspect of an individual, that is, the formation of an abstract interface.
-
An individual may have more than one abstract surface. There is a difference between an abstract body and an abstract surface.
Three oriented distinctions
-
Object orientation means that when we think about a problem, we think about an object in terms of its properties and methods.
-
Process-oriented means that we think of a problem in terms of a specific process (transactional process) and its implementation.
-
Interface design and non-interface design are for reuse technology, and object orientation (process) is not a problem. More embodiment is the overall architecture of the system
8.2. Develop with annotations
The essence is realized by reflection mechanism
At the bottom is the dynamic proxy
1. Annotations are implemented on the interface
@Select("select * from user")
List<User> getUser();
Copy the code
2. Bind interfaces to the core configuration file
<mappers>
<mapper class="com.luke.dao.UserMapper"/>
</mappers>
Copy the code
3. The test class
@Test
public void testGetUser(){
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUser();
for (User user : users) {
System.out.println(user.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sqlSession != null)
sqlSession.close();
}
}
Copy the code
8.3, CRUD
Automatic commit transaction:
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
Copy the code
Query:
@select (" Select * from user where id = #{id}") user selectUserById(@param ("id") int id);Copy the code
Feature:
@insert (" Insert into user (id,name, PWD) values (#{id},#{name},#{PWD})") int addUser(user user); @insert (" Insert into user (id,name, PWD) values (#{id},#{name},#{PWD})")Copy the code
Modification:
@update (" Update user set name=#{name}, PWD =#{PWD} where id =#{id}") int updateUser(user user); @update (" Update user set name=#{name}, PWD =#{PWD} where id =#{id}")Copy the code
Delete:
@delete (" Delete from user where id = #{id}") int deleteUser(@param ("id")int id);Copy the code
The @param annotation is used to give a name to a method parameter. Here are the principles of use:
-
In cases where the method accepts only one argument, @param is not used.
-
In cases where a method takes more than one parameter, it is recommended to always name the parameter using the @param annotation.
-
If the argument is a JavaBean, @param cannot be used.
-
Without the @param annotation, there can be only one parameter, and it is a Javabean.
9. Complex query (many-to-one)
9.1. Handle according to query nesting
Query statement:
<? The 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.luke.dao.StudentMapper"> <resultMap id="studentTeacher" type="student"> <result property="id" column="id"/> <result property="name" column="name"/> <association property="teacher" column="tid" javaType="teacher" select="getTeacher"/> </resultMap> <select id="getAllStudent" resultMap="studentTeacher"> select * from student; </select> <select id="getTeacher" resultType="teacher"> select * from teacher where id = #{tid}; </select> </mapper>Copy the code
9.2. Process according to result nesting
<resultMap id="studentTeacher2" type="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
<select id="getAllStudent2" resultMap="studentTeacher2">
select s.id sid, s.name sname, t.name tname from student s,teacher t where s.tid = t.id;
</select>
Copy the code
10. Complex query (one-to-many)
10.1. Nest according to the result
<? The 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.luke.dao.TeacherMapper"> <resultMap id="teacherStudent" type="teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <collection property="students" ofType="student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <result property="tid" column="tid"/> </collection> </resultMap> <select id="getTeacherById" resultMap="teacherStudent"> select s.id sid, s.name sname, t.name tname, t.id tid from student s,teacher t where s.tid = t.id and tid = #{id}; </select> </mapper>Copy the code
10.2. Nesting according to query
<resultMap id="teacherStudent2" type="teacher">
<result property="id" column="id"/>
<collection property="students" javaType="ArrayList" ofType="student" column="id" select="getStudengByTeacherId"/>
</resultMap>
<select id="getTeacherById2" resultMap="teacherStudent2">
select * from teacher where id = #{tid}
</select>
<select id="getStudengByTeacherId" resultType="student">
select * from student where tid = #{tid}
</select>
Copy the code
Dynamic SQL
Dynamic SQL is one of the powerful features of MyBatis.
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
11.1, the if
<select id="queryBlogIf" parameterType="map" resultType="blog"> select * from blog <where> <if test="title ! = null"> and title = #{title} </if> <if test="author ! = null"> and author = #{author} </if> </where> </select>Copy the code
11.2, Choose (when, otherwise)
<select id="queryBlogChoose" parameterType="map" resultType="blog"> select * from blog <where> <choose> <when test="title ! = null"> title = #{title} </when> <when test="author ! = null"> and author = #{author} </when> <otherwise> and views = #{views} </otherwise> </choose> </where> </select>Copy the code
11.3, the set
<! ParameterType ="map"> update blog <set> <if test="title! = null"> title = #{title}, </if> <if test="author ! = null"> author = #{author} </if> </set> where id = #{id}; </update>Copy the code
11.4, Foreach
<select id="queryBlogForeach" parameterType="map" resultType="blog"> select * from blog <where> <! -- Collection: specifies the collection attribute in the input object item: the object generated by each traversal Open: the concatenation string at the beginning of the traversal Close: the concatenation string at the end separator: the string to be concatenated between the traversal objects select * from blog where 1=1 and (id=1 or id=2 or id=3) --> <foreach collection="ids" item="id" open="and (" close=")" separator="or"> id=#{id} </foreach> </where> </select>Copy the code
11.5. SQL fragments
Extract:
<sql id="if-title-author"> <if test="title ! = null"> title = #{title} </if> <if test="author ! = null"> and author = #{author} </if> </sql>Copy the code
Introduction:
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
Copy the code
12, caching,
-
MyBatis includes a very powerful query caching feature that makes it very easy to customize and configure the cache. Caching can greatly improve query efficiency.
-
MyBatis system defines two levels of cache by default: level 1 cache and level 2 cache
-
By default, only level 1 caching is enabled. (SQLsession-level cache, also known as local cache)
-
Level 2 caching needs to be manually enabled and configured. It is namespace-level caching.
-
To improve scalability, MyBatis defines Cache interface Cache. We can customize the level 2 Cache by implementing the Cache interface
12.1. Level 1 Cache
Level 1 cache is also called local cache:
-
Data queried during the same session with the database is placed in the local cache.
-
In the future, if you need to obtain the same data, directly from the cache, do not have to query the database;
That is, the same query in the same session, the second and subsequent queries will read data from the cache
SqlSession session = MybatisUtils.getSession();
Copy the code
There are four cases of cache invalidation:
-
Different sqlSession
-
The same sqlSession, different query conditions
-
SqlSession is the same, two queries between the execution of the operation!
-
If sqlSession is the same, manually clear level-1 cache
12.2. Level 2 Cache
-
Level 2 cache is also called global cache, level 1 cache scope is too low, so was born level 2 cache
-
Namespace-level caching, one namespace for each level 2 cache;
-
Working mechanism
-
A session queries a piece of data and the data is placed in the level 1 cache of the current session.
-
If the current session is closed, the level 1 cache for that session is gone. But what we want is for the session to close and the data from the level 1 cache to be saved to the level 2 cache;
-
The new session queries the information and can retrieve the content from the secondary cache;
-
The data detected by different mapper is stored in its own cache (map).
Enable global cache:
<setting name="cacheEnabled" value="true"/>
Copy the code
Configuration use:
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
Copy the code
This configuration creates a FIFO cache, refreshed every 60 seconds, that can store up to 512 references to the resulting object or list, and the returned object is considered read-only
As long as level 2 caching is enabled, our queries in the same Mapper can get data in level 2 cache. All detected data is placed in level 1 cache by default. Data in the level 1 cache is transferred to the level 2 cache only after the session is committed or closed.