In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the MyBatis interview questions, the article is very detailed, has a certain reference value, interested friends must read it!
Introduction to MyBatis what is MyBatis?
MyBatis is an excellent persistence layer framework, a semi-ORM (object-relational mapping) framework that supports customized SQL, stored procedures, and high-level mapping. MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets. MyBatis can use simple XML or annotations to configure and map native types, interfaces, and Java's POJO (Plain Old Java Objects, plain old Java objects) to records in the database.
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 (POJO). To put it simply, ORM automatically persists objects in a program to a relational database by using metadata that describes the mapping between objects and databases.
Why is Mybatis a semi-automatic ORM mapping tool? What's the difference between it and full automation?
Hibernate is a fully automatic ORM mapping tool. When using Hibernate to query associated objects or associated collection objects, it can be obtained directly according to the object relational model, so it is fully automatic.
When querying associated objects or associated collection objects, Mybatis needs to write sql manually, so it is called semi-automatic ORM mapping tool.
Problems in traditional JDBC Development
Frequent creation and release of database connection objects can easily lead to a waste of system resources and affect system performance. You can use connection pooling to solve this problem. But using jdbc requires you to implement connection pooling yourself.
There is hard coding in sql statement definition, parameter setting and result set processing. In the actual project, the sql statement is likely to change. Once the change occurs, the java code needs to be modified and the system needs to be recompiled and reissued. It's hard to maintain.
It is hard-coded to use preparedStatement to pass parameters to occupancy symbols, because the where conditions of sql statements may be more or less, and it is not easy to modify the code to modify sql.
There is duplicate code in the result set processing, which is troublesome to deal with. It would be convenient if it could be mapped to a Java object.
What are the shortcomings of JDBC programming and how does MyBatis solve these problems?
1. The frequent creation and release of database links causes a waste of system resources and affects system performance. If you use database connection pool, you can solve this problem.
Solution: configure data link pooling in mybatis-config.xml and manage database connections using connection pooling.
2. The code is not easy to maintain when the Sql statement is written in the code, so the actual application of sql may change greatly, and the change of sql needs to change the java code.
Solution: separate the Sql statement from the java code in the XXXXmapper.xml file.
3. It is troublesome to pass parameters to sql statements, because the where conditions of sql statements may be more or less, and placeholders need to correspond to parameters one by one.
Solution: Mybatis automatically maps java objects to sql statements.
4. It is troublesome to parse the result set. The change of sql leads to the change of parsing code, and it needs to be traversed before parsing. It is more convenient to package the database record into pojo object parsing.
Solution: Mybatis automatically maps sql execution results to java objects.
Advantages and disadvantages of Mybatis
Advantages
Compared with traditional database access technologies, ORM has the following advantages:
Programming based on SQL statements is quite flexible and will not affect the existing design of the application or database. SQL is written in XML to decouple sql from program code and facilitate unified management. It provides XML tags, supports the writing of dynamic SQL statements, and can be reused.
Compared with JDBC, it reduces the amount of code by more than 50%, eliminates a lot of redundant code in JDBC, and does not need to switch the connection manually.
Good compatibility with various databases (because MyBatis uses JDBC to connect to databases, MyBatis supports all databases supported by JDBC)
Provide mapping tags to support ORM field mapping between objects and databases, and provide object relational mapping tags to support object relational component maintenance
Be able to integrate well with Spring
Shortcoming
The workload of writing SQL statements is large, especially when there are many fields and associated tables, there are certain requirements for developers to write SQL statements.
The SQL statement depends on the database, which leads to the poor portability of the database, and the database cannot be changed at will.
MyBatis framework is applicable to scenarios
MyBatis focuses on SQL itself and is a sufficiently flexible DAO-tier solution.
MyBatis will be a good choice for projects with high performance requirements or varied requirements, such as Internet projects.
The difference between Hibernate and MyBatis
Identical point
All of them are the encapsulation of jdbc, the framework of persistence layer, and all are used for the development of dao layer.
Differences
Mapping relation
MyBatis is a semi-automatic mapping framework, which configures the corresponding relationship between Java objects and the execution results of sql statements. The configuration of multi-table association relations is simple.
Hibernate is a framework for full table mapping, which configures the corresponding relationship between Java objects and database tables, and the configuration of multi-table association relations is complex.
SQL optimization and portability
Hibernate encapsulates SQL statements and provides features such as log, cache and cascading (cascading is more powerful than MyBatis). In addition, it also provides HQL (Hibernate Query Language) operation database, which supports database independence, but consumes more performance. If the project needs to support multiple databases, the amount of code development is small, but it is difficult to optimize SQL statements.
MyBatis needs to write SQL manually, supporting dynamic SQL, processing lists, dynamically generating table names, and supporting stored procedures. The development workload is relatively large. Using sql statements to operate the database directly does not support database independence, but SQL statements are easy to optimize.
Development difficulty and learning cost
Hibernate is a heavyweight framework with high learning barriers and is suitable for small and medium-sized projects with relatively stable needs, such as office automation systems.
MyBatis is a lightweight framework with low barriers to learning and use. It is suitable for large-scale projects with frequently changing requirements, such as Internet e-commerce systems.
Summary
MyBatis is a small, convenient, efficient, simple, direct, semi-automatic persistence layer framework.
Hibernate is a powerful, convenient, efficient, complex, indirect, fully automated persistence layer framework.
The principle of parsing and operation of MyBatis what are the MyBatis programming steps?
1. Create a SqlSessionFactory
2. Create SqlSession through SqlSessionFactory
3. Perform database operations through sqlsession
4. Call session.commit () to commit the transaction
5. Call session.close () to close the session
Please tell me how MyBatis works.
Before learning the MyBatis program, you need to understand how MyBatis works in order to understand the program. The working principle of MyBatis is as follows
1) read the MyBatis configuration file: mybatis-config.xml is the global configuration file of MyBatis and configures the running environment of MyBatis, such as database connection information.
2) load the mapping file. The mapping file is the SQL mapping file, which is configured with SQL statements to operate the database and needs to be loaded in the MyBatis configuration file mybatis-config.xml. Mybatis-config.xml files can load multiple mapping files, each corresponding to a table in the database.
3) construct a session factory: build a session factory SqlSessionFactory through configuration information such as the environment of MyBatis.
4) create a session object: a SqlSession object is created by the session factory, which contains all the methods for executing SQL statements.
5) Executor executor: the underlying MyBatis defines an Executor interface to operate the database, which will dynamically generate SQL statements that need to be executed according to the parameters passed by SqlSession, and is responsible for the maintenance of the query cache.
6) MappedStatement object: in the execution method of Executor API, there is a parameter of type MappedStatement, which encapsulates the mapping information and is used to store the id, parameters and other information of the SQL statement to be mapped.
7) input parameter mapping: input parameter types can be Map, List and other collection types, basic data types and POJO types. The input parameter mapping process is similar to the process that JDBC sets parameters on a preparedStatement object.
8) output result mapping: the output result type can be Map, List and other collection types, as well as basic data types and POJO types. The mapping process of the output result is similar to the parsing process of the result set by JDBC.
What is the functional architecture of MyBatis?
We divide the functional architecture of Mybatis into three layers:
API interface layer: provides external use of the interface API, developers through these local API to manipulate the database. As soon as the interface layer receives the call request, it will call the data processing layer to complete the specific data processing.
Data processing layer: responsible for specific SQL lookup, SQL parsing, SQL execution and result mapping processing. Its main purpose is to complete a database operation according to the called request.
Basic support layer: responsible for the most basic functional support, including connection management, transaction management, configuration loading, and caching, which are common things, extracted as the most basic components. It provides the most basic support for the upper data processing layer.
What is the framework design of MyBatis?
This picture is viewed from the top down. The initialization of MyBatis will deconstruct the class Configuration from the mybatis-config.xml configuration file, which is the red box in the figure.
(1) load configuration: the configuration comes from two places, one is the configuration file, and the other is the comments of Java code. The configuration information of SQL is loaded into MappedStatement objects (including incoming parameter mapping configuration, executed SQL statement, result mapping configuration) and stored in memory.
(2) SQL parsing: when the API interface layer receives the call request, it will receive the ID and the incoming object (which can be Map, JavaBean or basic data type) of the incoming SQL. The Mybatis will find the corresponding MappedStatement according to the ID of the SQL, and then parse the MappedStatement according to the passed parameter object. After parsing, you can get the final SQL statement and parameters to be executed.
(3) SQL execution: take the final SQL and parameters to the database for execution, and get the results of operating the database.
(4) result mapping: convert the results of operating the database according to the mapped configuration, which can be converted to HashMap, JavaBean or basic data types, and return the final result.
Why do you need precompilation?
Definition:
SQL precompilation means that the database driver compiles SQL statements and parameters before sending SQL statements and parameters to DBMS, so that DBMS does not need to recompile when it executes SQL.
Why do you need precompilation?
Object PreparedStatement is used in JDBC to abstract precompiled statements, and precompiled is used. The precompilation phase can optimize the execution of SQL. In most cases, the precompiled SQL can be executed directly, and the DBMS does not need to be compiled again. The more complex the SQL, the greater the compilation complexity, and the precompilation phase can merge multiple operations into one operation. At the same time, the object of the precompiled sentence can be reused. Cache a SQL precompiled PreparedStatement object, and next time for the same SQL, you can use the cached PreparedState object directly. Mybatis by default, all SQL is precompiled.
What Executor actuators does Mybatis have? What's the difference between them?
Mybatis has three basic Executor actuators, SimpleExecutor, ReuseExecutor, and BatchExecutor.
SimpleExecutor: every time a update or select is executed, a Statement object is opened, and the Statement object is closed immediately after use.
ReuseExecutor: execute update or select, use sql as key to find the Statement object, use it when it exists, create it if it doesn't exist, and do not close the Statement object after use, but put it in the Map for next use. In short, the Statement object is reused.
BatchExecutor: execute update (select is not supported without select,JDBC batches), add all sql to the batch (addBatch ()), wait for unified execution (executeBatch ()), it caches multiple Statement objects, each Statement object is addBatch (), and wait for the executeBatch () batch to be executed one by one. Same as JDBC batch.
Scope of action: these characteristics of Executor are strictly limited to the life cycle of SqlSession.
How do I specify which Executor executor to use in Mybatis?
In the Mybatis configuration file, you can specify the default ExecutorType executor type in the settings (settings), or you can manually pass ExecutorType type parameters, such as SqlSession openSession (ExecutorType execType), to DefaultSqlSessionFactory's method of creating SqlSession.
Configure the default actuator. SIMPLE is a normal executor; REUSE executors reuse preprocessing statements (prepared statements); BATCH executors reuse statements and perform batch updates.
Does Mybatis support delayed loading? If so, what is the principle of its implementation?
Mybatis only supports delayed loading of association associated objects and collection associated collection objects. Association refers to one-to-one and collection refers to one-to-many queries. In the Mybatis configuration file, you can configure whether to enable deferred loading of lazyLoadingEnabled=true | false.
Its principle is to use CGLIB to create a proxy object of the target object, and when the target method is called, enter the interceptor method, such as calling a.getB (). GetName (), the interceptor invoke () method finds that a.getB () is a null value, then the sql of the pre-saved query associated B object is sent separately, the B query is uploaded, and then a.setB (b) is called, so that the object b property of a has a value. Then complete the call to the a.getB () .getName () method. This is the basic principle of delayed loading.
Of course, not only Mybatis, but almost all of them, including Hibernate, support delayed loading on the same principle.
The difference between mapper # {} and ${}
# {} is a placeholder, precompiled; ${} is a splice, string replacement, no precompilation.
When Mybatis processes # {}, the # {} input parameter is passed as a string, and the # {} in SQL will be replaced with? Number, call the set method of PreparedStatement to assign the value.
When dealing with Mybatis, the original value is passed in, that is, when {}, the original value is passed in, that is, the original value is passed in, that is, {} is replaced with the value of the variable, which is equivalent to Statement compilation in JDBC.
After variable replacement, the variable corresponding to # {} is automatically enclosed in single quotes''; after variable replacement, the variable corresponding to ${} will not be enclosed in single quotation marks''.
# {} can effectively prevent SQL injection and improve system security; ${} can not prevent SQL injection
The variable substitution of # {} is in DBMS; the variable substitution of ${} is outside DBMS
How to write fuzzy query like statement
(1)'% ${question}% 'may cause SQL injection and is not recommended
(2) "%" {question} "%" Note: because # {… } when parsed into a sql statement, single quotation marks are automatically added to the outside of the variable, so here% you need to use double quotation marks, not single quotation marks, otherwise you will not be able to find any results.
(3) CONCAT ('%', # {question},'%') uses the CONCAT () function, which is recommended
(4) use bind tags
Select id,sex,age,username,password from person where username LIKE # {pattern} how to pass multiple parameters in mapper
Method 1: sequential parameter transfer method
Public User selectUser (String name, int deptId); select * from user where user_name = # {0} and dept_id = # {1}
The numbers in # {} represent the order in which the parameters are passed.
This method is not recommended, the SQL layer expression is not intuitive, and it is easy to make mistakes once the order is adjusted.
Methods 2:@Param annotated parameter transfer method
Public User selectUser (@ Param ("userName") String name, int @ Param ("deptId") deptId; select * from user where user_name = # {userName} and dept_id = # {deptId}
The name in # {} corresponds to the name decorated in parentheses in the annotation @ Param.
This method is relatively intuitive in the case of few parameters, and it is recommended to use.
Methods 3:Map transmission parameter method
Public User selectUser (Map params); select * from user where user_name = # {userName} and dept_id = # {deptId}
The name in # {} corresponds to the key name in Map.
This method is suitable for transferring multiple parameters, and the parameters are changeable and can be transferred flexibly.
Methods 4:Java Bean transmission parameter method
Public User selectUser (User user); select * from user where user_name = # {userName} and dept_id = # {deptId}
The name in # {} corresponds to the member attribute in the User class.
This method is intuitive, needs to build an entity class, is not easy to expand, needs to add attributes, but the readability of the code is strong, business logic processing is convenient, and it is recommended to use.
How to perform batch operations in Mybatis
Use foreach tags
Foreach is mainly used in building in conditions, which can iterate over a collection in a SQL statement. The main attribute of the foreach tag is item,index,collection,open,separator,close.
Item represents the alias of each element in the collection when iterating, a random variable name.
Index specifies a name that indicates the location of each iteration during the iteration, which is not commonly used
Open indicates what the statement begins with, and "(" is commonly used.
Separator indicates what symbol is used as a separator between each iteration. It is commonly used as ","
Close denotes what it ends with. It is often used as ")".
The most critical and error-prone attribute when using foreach is the collection attribute, which must be specified, but the value of this attribute is different in different cases. There are three main cases:
If a single parameter is passed and the parameter type is a List, the value of the collection attribute is list
If a single parameter is passed and the parameter type is an array array, the property value of collection is array
If multiple parameters are passed, we need to encapsulate them into a Map. Of course, a single parameter can also be encapsulated as a map. In fact, if you pass a parameter, it will also be encapsulated as a Map in the MyBatis.
The key of map is the parameter name, so the value of the collection attribute is the key of the passed List or array object in the map encapsulated by itself.
The specific usage is as follows:
/ / INSERT INTO emp (ename,gender,email,did) VALUES (# {emp.eName}, # {emp.gender}, # {emp.email}, # {emp.dept.id}) INSERT INTO emp (ename,gender,email,did) VALUES (# {emp.eName}, # {emp.gender}, # {emp.email}) is recommended # {emp.dept.id})
Use ExecutorType.BATCH
There are three kinds of ExecutorType built into Mybatis, and the default is simple. In this mode, it creates a new preprocessing statement for the execution of each statement, a single sql; is submitted, while the batch mode reuses the pre-processed statements, and all update statements are executed in batches. Obviously, batch performance will be better. However, the batch mode also has its own problems. For example, in the Insert operation, there is no way to get the self-increasing id before the transaction is committed, which does not meet the business requirements in a certain situation.
The specific usage is as follows
/ / batch save method test @ Test public void testBatch () throws IOException {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory (); / / sqlSession SqlSession openSession = sqlSessionFactory.openSession (ExecutorType.BATCH) that can perform batch operations; / / time before batch save long start = System.currentTimeMillis (); try {EmployeeMapper mapper = openSession.getMapper (EmployeeMapper.class); for (int I = 0; I < 1000) Mapper.addEmp (new Employee (UUID.randomUUID (). ToString (). Substring (0,5), "b", "1"));} openSession.commit (); long end = System.currentTimeMillis (); / / batch save the time after execution System.out.println ("execution time" + (end-start)) / / batch precompile sql once = "set parameters =" 10000 times = "execute 1 time 677 / / non-batch (precompilation = setting parameters = execution) =" 10000 times 1121} finally {openSession.close ();}}
Mapper and mapper.xml are as follows
Public interface EmployeeMapper {/ / batch save employee Long addEmp (Employee employee);} what are the ways to write Mapper?
First: interface implementation class inherits SqlSessionDaoSupport: to use this method, you need to write mapper interface, mapper interface implementation class, mapper.xml file.
(1) configure the location of mapper.xml in sqlMapConfig.xml
(2) define mapper interface
(3) implement class integration SqlSessionDaoSupport
In the mapper method, you can add, delete, modify and query data by this.getSqlSession ().
(4) spring configuration
The second is to use org.mybatis.spring.mapper.MapperFactoryBean:
(1) configure the location of mapper.xml in sqlMapConfig.xml. If the names of mapper.xml and mappre interfaces are the same and in the same directory, you do not need to configure them here.
(2) define the mapper API:
(3) namespace in mapper.xml is the address of mapper interface
(4) the method name in the mapper interface is consistent with the id of the statement defined in mapper.xml.
(5) defined in Spring
Third: use mapper scanners:
(1) mapper.xml file writing:
Namespace in mapper.xml is the address of the mapper interface
The method name in the mapper interface is consistent with the id of the statement defined in mapper.xml
If you keep the names of the mapper.xml and mapper interfaces the same, you do not need to configure them in sqlMapConfig.xml.
(2) define the mapper API:
Note that the file name of mapper.xml is the same as the interface name of mapper and is placed in the same directory
(3) configure mapper scanner:
(4) obtain the implementation object of mapper from the spring container after using the scanner.
What is the interface binding of MyBatis? What are the ways to implement it?
Interface binding is to define an interface arbitrarily in MyBatis, and then bind the methods in the interface to SQL statements. We can call the interface methods directly, so that we can have more flexible choices and settings than the original methods provided by SqlSession.
Interface binding can be implemented in two ways
By annotating binding, you add @ Select, @ Update and other annotations to the interface's methods, which contain Sql statements to bind
Bind by writing SQL in xml. In this case, to specify that the namespace in the xml mapping file must be the full path name of the interface. When the Sql statement is relatively simple, use annotation binding, when the SQL statement is more complex, use xml binding, generally use xml binding more.
What are the requirements when using MyBatis's mapper interface to call?
1. The method name of the Mapper interface is the same as the id of each sql defined in mapper.xml.
2. The input parameter type of the Mapper interface method is the same as the parameterType type of each sql defined in mapper.xml.
3. The output parameter type of the Mapper interface method is the same as the resultType type of each sql defined in mapper.xml.
4. Namespace in the Mapper.xml file is the classpath of the mapper interface.
In best practice, a Xml mapping file is usually written with a Dao interface corresponding to it. Excuse me, how does this Dao interface work? Can the method in the Dao interface be overloaded when the parameters are different?
Dao interface is what people often call Mapper interface. The full limit name of the interface is the value of namespace in the mapping file, the method name of the interface is the id value of MappedStatement in the mapping file, and the parameters in the interface method are the parameters passed to sql. The Mapper API does not implement the class. When calling the interface method, the full limit name of the interface + the method name concatenation string as the key value can uniquely locate a MappedStatement. For example: com.mybatis3.mappers.StudentDao.findStudentById, you can only find the MappedStatement whose namespace is id = findStudentById under com.mybatis3.mappers.StudentDao. In Mybatis, each, tag is resolved to a MappedStatement object.
The method in the Dao interface cannot be overloaded because it is the save and search strategy of the fully qualified name + method name.
The Dao interface works as a JDK dynamic proxy. The Mybatis runtime uses the JDK dynamic proxy to generate a proxy proxy object for the Dao interface. The proxy object proxy intercepts the interface method, executes the sql represented by MappedStatement, and returns the sql execution result.
In Mybatis's Xml mapping file, can different Xml mapping files be duplicated by id?
For different Xml mapping files, id can be repeated if namespace is configured; if namespace is not configured, id cannot be repeated; after all, namespace is not necessary, it's just a best practice.
The reason is that namespace+id is used as the key of Map, if there is no namespace, only id is left, then id repetition will cause the data to overwrite each other. With namespace, the natural id can be repeated. If the namespace is different, the namespace+id is different.
Briefly describe the mapping relationship between Mybatis's Xml mapping file and Mybatis internal data structure?
Answer: Mybatis encapsulates all Xml configuration information inside the All-In-One heavyweight object Configuration. In the Xml mapping file, the tag is resolved to a ParameterMap object, and each of its child elements is resolved to a ParameterMapping object. The tag is resolved to a ResultMap object, and each of its child elements is resolved to a ResultMapping object. Each, tag will be resolved to a MappedStatement object, and the sql within the tag will be resolved to a BoundSql object.
How does Mybatis encapsulate the sql execution result as a target object and return it? What are the forms of mapping?
The first is to use tags to define the mapping between column names and object attribute names one by one.
The second is to use the alias function of the sql column to write the column alias as an object property name, such as T_NAME AS NAME, the object property name is generally name, lowercase, but the column name is not case-sensitive, Mybatis will ignore the column name case, intelligently find the corresponding object property name, you can even write as T_NAME AS NaMe,Mybatis can work normally.
After having the mapping relationship between column name and attribute name, Mybatis creates the object through reflection, and uses the properties reflected to the object to assign values one by one and return them. Those attributes that can not find the mapping relationship cannot complete the assignment.
Apart from the common select | insert | updae | delete tags in the Xml mapping file, what other tags are there?
There are many other tags, plus nine tags of dynamic sql, trim | where | set | foreach | if | choose | when | otherwise | bind, etc., in which sql fragment tags are introduced into sql fragments through tags to generate policy tags for primary keys that do not support self-increment.
In the Mybatis mapping file, if the A tag references the content of the B tag through include, can the B tag be defined after the A tag, or must it be defined in front of the A tag?
Although Mybatis parses the Xml mapping file sequentially, the referenced B tag can still be defined anywhere, and Mybatis can correctly identify it.
The principle is that Mybatis parses the A tag and finds that the A tag refers to the B tag, but the B tag has not yet been parsed and does not yet exist. At this point, Mybatis marks the A tag as unresolved, and then continues to parse the remaining tags, including the B tag. When all the tags are parsed, Mybatis will re-parse those tags that are marked as unresolved. When the A tag is parsed again, the B tag already exists. The A tag can be parsed normally.
Advanced query MyBatis to achieve one-to-one, one-to-many there are several ways, how to operate?
There are federated queries and nested queries. A federated query is a federated query of several tables, which can be queried only once. It can be accomplished by configuring one-to-one and one-to-many classes in the association,collection node in resultMap.
The nested query is to query a table first, and then query the data in another table according to the foreign key id of the results in this table, also by configuring association,collection, but the query of another table is configured through the select node.
Can Mybatis map Enum enumerated classes?
Mybatis can map enumerated classes, not only enumerated classes can be mapped, Mybatis can map any object to a column of the table. The mapping method is to customize a TypeHandler and implement the setParameter () and getResult () interface methods of TypeHandler.
TypeHandler has two functions, one is to complete the conversion from javaType to jdbcType, and the other is to complete the conversion from jdbcType to javaType, which is embodied in two methods: setParameter () and getResult (), which represent setting sql question mark placeholder parameters and getting column query results, respectively.
What does dynamic SQLMybatis dynamic sql do? What are the dynamic sql? Can you briefly describe the implementation principle of dynamic sql?
Mybatis dynamic sql allows us to write dynamic sql in the form of tags in the Xml mapping file to complete the function of logical judgment and dynamic splicing of sql. Mybatis provides nine kinds of dynamic sql tags trim | where | set | if | choose | when | otherwise | bind.
Its execution principle is that it uses OGNL to calculate the value of the expression from the sql parameter object, and dynamically splices the sql according to the value of the expression, so as to complete the function of dynamic sql.
How is the plug-in module Mybatis paginated? What is the principle of the paging plug-in?
Mybatis uses the RowBounds object for paging, which is memory paging for ResultSet result sets rather than physical paging. You can write parameters with physical paging directly within sql to complete physical paging, or you can use paging plug-ins to complete physical paging.
The basic principle of the paging plug-in is to use the plug-in interface provided by Mybatis to implement the custom plug-in, intercept the sql to be executed in the plug-in interception method, then rewrite the sql, and add the corresponding physical paging statements and physical paging parameters according to the dialect dialect.
For example: select * from student, after intercepting sql, rewrite as: select t.* from (select * from student) t limit 0,10
This paper briefly describes the operation principle of plug-ins in Mybatis and how to write a plug-in.
Mybatis can only write plug-ins for ParameterHandler, ResultSetHandler, StatementHandler, and Executor interfaces. Mybatis uses JDK's dynamic proxy to generate proxy objects for interfaces that need to be intercepted to achieve the interface method interception function. Whenever the methods of these four interface objects are executed, they will enter the intercept method, specifically the invoke () method of InvocationHandler. Of course, it will only intercept those methods that you specify need to be intercepted.
Implement Mybatis's Interceptor interface and override the intercept () method, and then annotate the plug-in to specify which interface and which methods to intercept. Remember, don't forget to configure the plug-in you wrote in the configuration file.
The primary and secondary caches of Mybatis.
1) first-level cache: PerpetualCache-based HashMap local cache, whose storage scope is Session. After Session flush or close, all Cache in the Session will be cleared, and first-level cache will be turned on by default.
2) the mechanism of the second-level cache is the same as that of the first-level cache, except that the storage scope is Mapper (Namespace) and the storage source can be customized, such as Ehcache. The second-level cache is not enabled by default. To enable the second-level cache, you need to implement the Serializable serialization interface (which can be used to save the state of the object) to use the secondary cache property class, which can be configured in its mapping file.
3) for the cache data update mechanism, when the C/U/D operation is performed in a certain scope (first-level cache Session/-second-level cache Namespaces), by default all caches in the select under that scope will be clear.
The above is all the contents of the article "what are the MyBatis interview questions?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.