Mybatis cache, super detailed! Includes: lazy loading, immediate loading, cache, first-level cache, second-level cache, custom cache

Mybatis cache

Lazy (lazy) loading and immediate loading

  • Delayed (lazy) loading

    Initiate queries only when the data is actually used, do not query when not in use, load on demand (also called lazy loading)

    ? for example:

    ? When querying class information, there will be many students in each class (assuming there are 100 students in each class). If we only check the class information, but the student objects will also be loaded into the memory, it will cause waste.

    ? So we need to do lazy loading. When we really need to view the student information in the class, we are loading the student information in the class.

    Usually: One-to-many or many-to-many requires lazy loading

  • Load now

    No matter whether the information is used or not, as long as the call is made, the query will be initiated and loaded immediately

    ? When we query student information, we need to know which class the student is in, so we need to query the class information immediately

    Usually: Immediate loading is required when one-to-one or many-to-one situations

Case:

For example, now query the student table

mapper.java

@Select("select * from student")
public List<Student> findStudentAndClass();

Implementation class:

List<Student> slist = stuMapper.findStudentAndClass();
Student s = slist.get(0);
System.out.println(s);

The implementation class only needs the first data in the collection, and it should only need to query the class corresponding to the student, but it will find out all classes, which is immediate loading. Immediate loading means that regardless of whether the data is needed, as soon as a query is made, the related data will be queried together.

Lazy loading will only query the class corresponding to the first data. It will only query when it is used and not when it is not in use.

Set lazy loading

Add to the main configuration file. The tag should be below and above

<settings>
<setting name="lazyLoadingEnabled" value="true"/>
    <!-- Enable lazy loading -->
<setting name="aggressiveLazyLoading" value="false"/>
   <!-- Turn off level loading -->
</settings>

Hierarchical loading: Hierarchical loading will only occur after lazy loading is turned on (it was enabled by default before 3.4.1). It will load other unused items into the memory during free time to achieve all loading.

After turning on lazy loading, only the data used will be queried.

Enable lazy loading in dynamic sql: fetchType attribute

@Results({
@Result(column = "classid", property = "classid"),
@Result(property = "bj",column = "classid",
one = @One(select = "com.ape.mapper.BanjiMapper.findBanjiByClassid",fetchType = FetchType.LAZY) )
\t\t\t
})
@Select("select * from student")
public List<Student> findStudentAndClass();

The value of the fetchType attribute is three enumeration values, assignment eg: fetchType = FetchType.LAZY (FetchType.)

  1. DEFAULT: What is loaded in the main configuration file is loaded by default.
  2. EAGER: Load now
  3. LAZY: lazy loading, delayed loading

Add attribute fetchType=” ” in in xml

<association property="" select="" fetchType="lazy" >
</association>

Caching

  • cache

    Cache, a buffer for data exchange. When an application needs to read data, it first takes the data out of the database and places it in the buffer. The application reads the data from the buffer.

    Features: The data retrieved from the database is stored in memory and can be read and used quickly.

    Limitations: No need to obtain from the database when reading, the data may not be the latest

  • hits and misses

    1. Hit: The required data is found in the cache

    2. Miss: The required data was not found in the cache.

  • The meaning of mybatis cache

    Reduce access to the database, reduce time resources, and improve efficiency

  • Caching applicability

    1. Suitable for caching

      ? Frequently queried and infrequently changed

      ? The accuracy of the data has little impact on the final result.

      ? For example: a company introduction, news, etc.

    2. Not suitable for caching

      ? Data that changes frequently

      ? The accuracy of the data has a great impact on the final result.

      ? For example, commodity inventory, stock market prices, etc.

Level 1 cache

  • Session session-level cache, within a session operation

  • Enabled by default, the first-level cache is only relative to the same SqlSession object.

For example: in the same sqlsession object, if two identical sql are executed, the database will not be queried for the second time, but the cached data of the first query will be directly called.

Mapper.java

@Select("select * from student where sid = #{v}")
public Student findStudentBySid(int sid);

Implementation class

SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);
// Query student No. 5
Student s = stuMapper.findStudentBySid(5);
System.out.println(s);
// Business logic...
for(int i = 0; i< 100; i + + ) {<!-- -->
System.out.print(i);
}
// Query student No. 5 again
Student s2 = stuMapper.findStudentBySid(5);

The second query of s2 will not execute the sql statement and directly return the results in the cache.

The output System.out.print(s1 == s2); is true, indicating that s2 gets the data in the cache.

  • Level 1 cache

When querying the first-level cache, the cache is first searched instead of the database. The query results are cached first and then returned to the user.

Workflow


Note: First-level cache failure

  1. Use different sqlsession

  2. The same sqlsession single query conditions are different

  3. Any addition, deletion, modification, commit(), close() operations were performed during the two queries of the same sqlsession.

  4. The cache was manually cleared during two queries in the same sqlsession.

    sqlsession.clearCache(); // Clear cache
    

Secondary loading (basically not used)

The largest scope of the first-level cache is one sqlsession. If multiple SqlSession needs to share the cache, a second-level cache is needed.

  • Second level cache: Mapper level, as long as it is the same Mapper, no matter how many SqlSession is used to operate, the data is shared. Multiple different SqlSession can share the second level cache. MyBatis second level cache is turned off by default, you need to use It can be turned on manually. The second-level cache can also use a third-party cache. For example, use Ehcache as the second-level cache.

  • Level 2 cache configuration

    1. main configuration file

    2. annotation

  • Second level cache summary

    1. Compared with the first-level cache, Mybatis’s second-level cache realizes the sharing of cached data and is more controllable.
    2. There is a high possibility of erroneous data, design flaws, and strict conditions for safe use.
    3. In a distributed environment, incorrect data will inevitably be read, so it is not recommended.

Custom cache

  • Custom cache classification

    1. Implement cache interface

      Implement org. apache. ibatis. cache. Cache interface custom cache

    2. Introduce third-party cache

      Introduce third-party memory libraries such as Redis as MyBatis cache

The difference between first-level cache and second-level cache

  1. The first-level cache is a SqlSession-level cache. Its scope is the same SqlSession. Multiple queries in the same SqlSession will share the same cache. The second-level cache is a Mapper-level cache. Its scope is the same Mapper. Multiple queries in the same Mapper will share the same cache.
  2. The first-level cache is enabled by default and does not require manual configuration. The second-level cache needs to be configured manually and needs to be added to the Mapper.xml file.
  3. The life cycle of the first-level cache is as long as SqlSession. When SqlSession is closed, the first-level cache will also be cleared. The life cycle of the second-level cache is as long as the MapperFactory. When the application is closed, the second-level cache will also be cleared.
  4. The first-level cache can only be used for multiple queries in the same SqlSession and cannot be used for queries across SqlSession. The second level cache can be used for cross-SqlSession queries, and multiple SqlSession can share the same second level cache.
  5. The first-level cache is thread-private, and cached data between different SqlSession will not interfere with each other. The second-level cache is shared by threads. Multiple SqlSession can share the same second-level cache. Thread safety issues need to be considered.