Several questions about mybatis


1. What is the difference between #{} and ${} in MyBatis?

#{} is pre-compilation processing, ${} means string splicing. The mysql engine will automatically translate #{} into? Then the parameters are pre-compiled through preparedStatement, which can prevent sql injection, but ${} cannot prevent string injection.

2. How many paging methods does MyBatis have? What is the difference between them?

There are two main paging methods:

  • Logical paging: paging through the built-in RowBounds. Query a lot of data at once, and then retrieve the paged data in the results, which will increase memory consumption, easily cause memory overflow, and put more pressure on the database.
  • Physical paging: Query a specified number of data by manually encoding sql, or through the PageHelper paging plug-in. This paging method can effectively prevent memory overflow

3. Does RowBounds query all results at once? why?

No, RowBounds will not find out all the data at one time. Because mybatis is a package of jdbc, and the jdbc driver has a Fetch Size configuration, this configuration controls the maximum amount of data that can be queried from the database at a time. Generally speaking The default value of this parameter is 1000, which means that at most 1000 data can be found from the database each time. When you click next, it will load another 1000 data from the database (if there are 1,000 more) , So you can effectively reduce the risk of memory overflow.

4. Does MyBatis support lazy loading? What is the principle of lazy loading?

MyBatis supports lazy loading, just set lazyLoadingEnabled=true.
The principle of lazy loading is to trigger loading when calling, rather than loading information when initializing. For example, a.getB().getName(), there is no data of object b in the a object. At this time, when the getB() method is called, the query sql stored in jdbc will be called , which will trigger the saved association b separately. The SQL of the object is to query the relevant data of the b object from the database, and use the setter method to assign it, and then get the name property of the b object to get the data. The above is the basic principle of lazy loading.

Fifth, what about MyBatis's first-level cache and second-level cache?

Level 1 cache: HashMap local cache based on PerpetualCache. Its life cycle is consistent with SQLSession. If there are multiple SQLSessions or database operations in a distributed environment, dirty data may appear. After Session flush or close, all Caches in the Session will be emptied, and the first level cache is enabled by default.
Second-level cache: HashMap local cache based on PerpetualCache. The difference is that its storage scope is Mapper level. If multiple SQLSessions need to share the cache, you need to use the second-level cache, and the second-level cache can customize the storage source , Such as Ehcache. The second-level cache is not turned on by default. To enable the second-level cache, the use of the second-level cache attribute class needs to implement the Serializable serialization interface (which can be used to save the state of the object).

6. What are the differences between MyBatis and hibernate?

1. Flexibility: MyBatis is more flexible, you can write SQL statements yourself, which is more convenient to use.
2. Portability: MyBatis has a lot of SQL written by itself, because the SQL of each database can be different, so the portability is relatively poor.
3. The threshold for learning and use: MyBatis is relatively simple to get started, and the threshold for use is also lower.
4. Second-level cache: hibernate has a better second-level cache, and its second-level cache can be replaced by a third-party second-level cache.

7. What executors (Executor) does MyBatis have?

SimpleExecutor: open a Statement object every time update or select is executed, and close the Statement object as
soon as it is used up; ReuseExecutor: execute update or select, use SQL as the key to find the Statement object, use it if it exists, create it if it does not exist, and do not close it after use The Statement object is placed in the Map for the next use. In short, it is to reuse the Statement object;
BatchExecutor: execute update (no select, jdbc batch processing does not support select), add all SQL to the batch (addBatch()), wait for unified execution (executeBatch()), It caches multiple Statement objects, and each Statement object waits for executeBatch() batch processing one by one after addBatch() is completed, which is the same as jdbc batch processing.

8. What is the realization principle of the MyBatis paging plug-in?

The basic principle of the paging plug-in is to use the plug-in interface provided by MyBatis to implement a custom plug-in, intercept the SQL to be executed in the plug-in's interception method, then rewrite the SQL, and add the corresponding physical paging statement and physical paging parameters according to the dialect dialect.

9. How to write a custom plug-in for MyBatis?

Implementation principle of
custom plug-in MyBatis custom plug-in intercepts the four major objects of MyBatis (Executor, StatementHandler, ParameterHandler, ResultSetHandler):
Executor: intercepts the internal executor, which is responsible for calling the StatementHandler to operate the database and automatically mapping the result set through the ResultSetHandler. In addition, it also handles the operation of the second-level cache;
StatementHandler: intercepts the processing of SQL syntax construction, it is the object of MyBatis to execute SQL scripts directly with the database, and it also implements the first-level cache of MyBatis;
ParameterHandler: intercepts the processing of parameters;
ResultSetHandler: Intercept the processing of the result set.

Custom plug-in implementation key
MyBatis plug-in must implement the Interceptor interface. The methods contained in the interface are as follows:

public interface Interceptor {
    
    
	Object intercept(Invocation invocation) throws Throwable;
	Object plugin(Object target);
	void setProperties(Properties properties);
}

The setProperties method is to configure custom related properties when configuring the plug-in in MyBatis, namely: the parameter configuration of the interface implementation object; the
plugin method is used by the plug-in to encapsulate the target object, through this method we can return the target object itself, or return One of its agents can decide whether to intercept and then decide what kind of target object to return. The official example is provided: return Plugin. wrap(target, this); The
intercept method is the method to be executed when intercepting.
Custom plug-in implementation example
Official plug-in implementation:

@Intercepts({
    
    @Signature(type = Executor. class, method = "query",
args = {
    
    MappedStatement. class, Object. class, RowBounds. class, ResultHandler. class})})
public class TestInterceptor implements Interceptor {
    
    
	public Object intercept(Invocation invocation) throws Throwable {
    
    
		Object target = invocation. getTarget(); //被代理对象
		Method method = invocation. getMethod(); //代理方法
		Object[] args = invocation. getArgs(); //方法参数
		// do something . . . . . . 方法拦截前执行代码块
		Object result = invocation. proceed();
		// do something . . . . . . . 方法拦截后执行代码块
		return result;
	}
	
	public Object plugin(Object target) {
    
    
		return Plugin. wrap(target, this);
	}
}

10. Talk about the initialization principle and execution principle of MyBatis

Initialization principle:

  1. Call the build(inputStream) method of the SqlSessionFactoryBuilder object;
  2. SqlSessionFactoryBuilder will create an XMLConfigBuilder object based on the input stream inputStream and other information;
  3. SqlSessionFactoryBuilder calls the parse() method of the XMLConfigBuilder object;
  4. The XMLConfigBuilder object returns the Configuration object;
  5. SqlSessionFactoryBuilder creates a DefaultSessionFactory object based on the Configuration object;
  6. SqlSessionFactoryBuilder returns the DefaultSessionFactory object to the Client for use by the Client;

Implementation principle:
Step 1, read the configuration file and cache it to the Configuration object to create a SqlSessionFactory;
Step 2, the execution process of SqlSession, mainly uses reflection mechanism and dynamic proxy to complete the underlying call of jdbc.

SqlSessionFactoryBuilder : The constructor of SqlSessionFactory, used to create SqlSessionFactory . The Builder design pattern
Configuration is adopted: This object is all mybatis configuration information in the mybatis-config.xml file.
SqlSessionFactory : SqlSession factory class. Create the SqlSession object in the form of a factory, using the Factory factory design pattern
XmlConfigParser : responsible for parsing the mybatis-config.xml configuration file into a Configuration object, which is used by SqlSessonFactoryBuilder to create SqlSessionFactory

Guess you like

Origin blog.csdn.net/qq_42697271/article/details/113853463