Mybatis execution process, caching principle and related interview questions

Time:2022-1-19

1、 Mybatis execution process

Specifically analyze how mybatis operates the database!

Mybatis execution process, caching principle and related interview questions

1. Define the path of our core configuration file. This path is found from target / classes!

 String config = "mybatis-config.xml" ;

Mybatis execution process, caching principle and related interview questions

2. Read the file represented by this config

 InputStream inputStream= Resources.getResourceAsStream(config);

3. Create sqlsessionfactorybuilder object

SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

4. Create sqlsessionfactory object

SqlSessionFactory sessionFactory = builder.build(inputStream);

5. Obtain the sqlsession object from sqlsessionfactory

SqlSession sqlSession = sessionFactory.openSession();

6. [key] the identification of the SQL statement to be executed. ID value of namespace + SQL tag in SQL file

String sqlId = "com.sqx.dao.UserMapper.getUserById";

Mybatis execution process, caching principle and related interview questions

7. Execute the SQL statement, find the statement through sqlid and execute it!

List<Object> objects = sqlSession.selectList(sqlId);

8. Close sqlsession

sqlSession.close();

summary

Mybatis config. Will be loaded when myabtis starts XML, the core configuration file, obtains the information of the database to be operated and our mapper file, and then saves it in the form of data flow and transmits it to sqlsessionfactorybuilder to create the sqlsessionfactory factory corresponding to the database. The factory produces sqlsession. This sqlsession contains the methods of adding, deleting and modifying the database. We need tonamespace + sqlIdTo determine which SQL we are executing. This step can be performed through sqlseesion Getmapper () gets the interface and binds our SQL by calling the method of the interface, includingnamespace + sqlId), execute the corresponding SQL statement!

2、 Mybatis cache

Mybatis cache, whether level 1 cache or level 2 cache, is a local cache, which will occupy the memory of the JVM. Once Java stops, the cache will become invalid!

1. L1 cache

summary

  • The L1 cache is saved in our sqlsession
  • As long as it is the same sqlsesisson (the session established with the database), the same cache will be used
  • The first level cache is enabled by mybatis by default!

The following is a test of the L1 cache:

Mybatis execution process, caching principle and related interview questions

View our test results

Mybatis execution process, caching principle and related interview questions

Using different sqlsession test data, make the following modifications!

Mybatis execution process, caching principle and related interview questions

Let’s review the test results again

Mybatis execution process, caching principle and related interview questions
It is concluded that our L1 cache is only valid in the same sqlsession!

2. L2 cache

summary

L2 cache, also known as “global cache”, is a cache based on namespace level. A namespace corresponds to a L2 cache!

Working mechanism:

  • A session queries a piece of data, which will be placed in the L1 cache,
  • When our session is closed, we will move this data from the L1 cache to the L2 cache, and the new session can find this data in the L2 cache!
  • When different sessions query different namespaces, they will cache the data in different namespaces into their corresponding cache (map)!

Use steps:

Just add it to the namespace that needs to use the cache< cache/>that will do

<!-- In the current mapper Use L2 cache in XML and configure related parameters -- >
<cache  eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>

Eviction: cache recycling policy
	LRU (longest unused), LFU (least accessed), FIFO (default), soft (soft reference), weak (weak reference)
Flush interval: cache refresh interval
	How often is the cache emptied? It will not be emptied by default. Set a millisecond value
Readonly: read only
Size: how many elements are stored in the cache

We can also implement custom caching through configuration

<!--   The essence of enabling the secondary cache of mybatis is that mybatis helps us implement the cache interface provided by ourselves,
That is, the type attribute of the cache tag specifies the cache policy by default 	-->

 <cache type=""/>    
 <!-- This is essentially the writing method. We can modify the type to select the custom cache policy -- >
 <cache type="rg.apache.ibatis.cache.impl.PerpetualCache"/>

3. Cache principle

As shown in the figure

Mybatis execution process, caching principle and related interview questions

Cache execution process

  • When our SQL is executed, first go to the L2 cache namespace to check whether there is a cache,
  • Then, if the L2 cache does not exist, check whether it exists in the L1 cache in the current sqlsession,
  • Finally, if both the first and second level caches do not exist, query the database,
  • Then the query results will be saved in our first level cache,
  • When the current session (sqlsession) ends, the data in the L1 cache will be synchronized to our L2 cache

3、 Related interview questions

1. Why is mybatis a semi-automatic ORM mapping tool? What is the difference between it and automatic?

What is ORM

ORM (object relational mapping), object relational mapping, is a technology to solve the mapping relationship between relational database data and simple Java objects (POJOs).

Why is mybatis a semi-automatic ORM mapping tool? What is the difference between it and automatic?

  • First, likeHibernate、JPAThis is a fully automatic ORM mapping tool. When using hibernate to query Association objects or association collection objects, it can be obtained directly according to the object relationship model, so it is fully automatic.
  • When mybatis queries Association objects or association collection objects, it needs to write SQL manually. Therefore, it is called semi-automatic ORM mapping tool.
  • In other words, the main reason why mybatis is a semi-automatic ORM is,It needs to generate SQL manually or plug-ins in XML or annotations to bind the SQL execution results to the object mapping.

2. Briefly describe the execution process of mybatis?

  • Mybatis takes a sqlsessionfactory instance as the core. The sqlsessionfactory instance can be obtained through sqlsessionfactorybuilder.
  • Sqlsessionfactory builder can build a sqlsessionfactory instance from an XML configuration file or a pre configured configuration instance.
  • Sqlsessionfactory instance factory can produce sqlsession, which provides all the methods required to execute SQL commands in the database.

3. Tell me about the advantages and disadvantages of mybatis?

advantage

  • Based on SQL statements, it is quite flexible. SQL is written in XML files, which removes the coupling between SQL and program code and facilitates unified management
  • The redundant code of JDBC is eliminated and can be well integrated with spring

shortcoming

  • The workload of writing SQL statements is large, especially when there are many fields and associated tables, which has certain requirements for the SQL statement skills of developers
  • SQL statements depend on the database, resulting in poor database portability. The database cannot be replaced at will

4. What is the difference between #{} and ${}?

  • #{} is a placeholder, precompiled, ${} is a splicer, string replacement, no precompiled processing
  • When mybatis processes #{}, the parameter passed in by #{} is a string, which will replace #{} in SQL with? Call the set method of Preparedstatement to assign a value
  • Myabtsi is processing
  • #{} can effectively prevent SQL injection and improve system security through compilation preprocessing, ${} can not prevent SQL injection

5. What is the role of mybatis’s dynamic SQL? What is the principle of execution? What are the common labels?

  • The dynamic SQL of mybatis can be written in the form of tags in the XML Mapping file
  • Execution principle: complete logical judgment according to the value of parameter expression, and dynamically splice SQL
  • Mybatis provides nine dynamic SQL Tags: trim, where, set, foreach, if, choose, when, otherwise, and bind