Introduction of MyBatis

What is MyBatis?

MyBatis is an excellent persistence layer framework, a semi-ORM (Object relational Mapping) framework, which supports customized SQL, stored procedures and advanced mapping. MyBatis avoids almost all of the JDBC code and manual setting of parameters and fetching result sets. MyBatis can use simple XML or annotations to configure and map native types, interfaces, and Java’s Plain Old Java Objects (POJOs) to records in the database.


What is the ORM

Object Relational Mapping (ORM) is a technology to solve the Mapping relationship between Relational database data and simple Java objects (POJOs). Simply put, ORM automatically persists an object in a program to a relational database by using metadata that describes the mapping between the object and the database.


Mybatis semi-automatic ORM mapping toolWhat’s the difference between it and automatic?

Hibernate is a fully automated ORM mapping tool. When using Hibernate to query associated objects or associated collection objects, it can be directly retrieved based on the object relational model, so it is fully automated.


While Mybatis needs to write SQL manually when querying associated objects or associated collection objects, so it is called semi-automatic ORM mapping tool.


Problems with traditional JDBC development

Frequently creating or releasing database connection objects wastes system resources and affects system performance. Connection pooling can be used to solve this problem. But using JDBC requires you to implement connection pooling yourself.

SQL statement definition, parameter setting, result set processing are hard coded. In actual projects, SQL statements are likely to change. Once changes occur, Java code needs to be modified, and the system needs to be recompiled and re-published. Difficult to maintain.

Hard coding exists in transferring parameters to possession bit symbols in preparedStatement, because the WHERE conditions of SQL statements are not necessarily, which may be more or less. Modifying SQL requires modifying codes, making the system difficult to maintain.

Result set processing exists duplicate code, processing trouble. It would be convenient if you could map to Java objects.

What are the weaknesses of JDBC programming, and how does MyBatis address them?

1. Frequent creation and release of database links waste system resources and thus affect system performance. This problem can be solved by using database connection pool.


Solution: Configure the data link pool in mybatis-config. XML and use the connection pool to manage database connections.


2, THE Sql statement written in the code causes the code is not easy to maintain, the actual application of Sql changes may be large, Sql changes need to change the Java code.


Solution: Separate the Sql statement configuration from the Java code in xxxxmapper.xml.


3. It is difficult to pass parameters to SQL statements, because SQL statements where conditions are not necessarily, may be more or less, placeholders need to correspond with parameters one by one.


Solution: Mybatis automatically maps Java objects to SQL statements.


4, the result set parsing is troublesome, SQL changes lead to parsing code changes, and before parsing need to traverse, if the database records can be encapsulated into POJO object parsing is more convenient.


Solution: Mybatis automatically maps SQL execution results to Java objects.


Mybatis pros and cons

advantages


ORM has the following advantages over traditional database access technologies:


Based on SQL statement programming, quite flexible, will not cause any impact on the existing design of the application program or database, SQL written in XML, remove the COUPLING of SQL and program code, easy to unified management; Provides XML tags that support writing dynamic SQL statements and can be reused

More than 50% less code than JDBC, eliminating a lot of JDBC redundant code, and no need to manually switch the connection

MyBatis uses JDBC to connect to the database, so as long as JDBC support database MyBatis all support

Provide mapping labels to support ORM field relational mapping between objects and databases; Provides object-relational mapping labels to support object-relational component maintenance

Integrates well with Spring

disadvantages


SQL statement writing workload is large, especially when there are many fields, associated tables, for developers to write SQL statement skills have certain requirements

SQL statements depend on databases, which leads to poor database portability. Therefore, databases cannot be replaced at will

Application scenarios of the MyBatis framework

MyBatis focuses on SQL itself and is a flexible DAO layer solution.

MyBatis will be a good choice for projects with high performance requirements or variable requirements, such as Internet projects.

The difference between Hibernate and MyBatis

The same


Both encapsulate JDBC, are frameworks for the persistence layer, and are used for dao layer development.


The difference between


The mapping relationship


MyBatis is a semi-automatic mapping framework that configures the mapping between Java objects and SQL statement execution results. It is easy to configure multi-table association relationships

Hibernate is a full table mapping framework, which configures the corresponding relationship between Java objects and database tables

SQL optimization and portability


Hibernate encapsulates SQL statements, provides logging, caching, cascading (cascading is more powerful than MyBatis) and other features. In addition, Hibernate Query Language (HQL) operation database is provided, which has good support for database independence, but will consume more performance. If the project needs to support multiple databases, the amount of code development is less, but SQL statement optimization is difficult.

MyBatis needs to manually write SQL, support dynamic SQL, process lists, dynamically generate table names, support stored procedures. The development workload is relatively large. Directly use SQL statements to operate the database, does not support database independence, but SQL statement optimization is easy.

Ease of development and cost of learning


Hibernate is a heavyweight framework, learning to use high threshold, suitable for relatively stable demand, small and medium-sized projects, such as: office automation system


MyBatis is a lightweight framework with a low threshold for learning and using. It is suitable for large-scale projects with frequent demand changes, such as Internet e-commerce system


conclusion


MyBatis is a compact, convenient, efficient, simple, direct, semi-automated persistence layer framework.


Hibernate is a powerful, convenient, efficient, complex, indirect and fully automated persistence layer framework.


Analysis and operation principle of MyBatis

What does MyBatis programming step look like?

Create SqlSessionFactory


Create SqlSession with SqlSessionFactory


3. Perform database operations using SQLSession


Call session.mit () to commit transaction


5. Call session.close() to close the session


Please tell me how MyBatis works

Before learning MyBatis program, you need to understand the working principle of MyBatis, so as to understand the program. How MyBatis works is shown below




1) Read the MyBatis configuration file: MyBatis -config. XML is the global configuration file of MyBatis, which configures the operating environment and other information of MyBatis, such as database connection information.


2) Load the mapping file. A mapping file is an SQL mapping file that contains SQL statements for operating the database and must be loaded in the MyBatis configuration file MyBatis -config. XML. The mybatis-config. XML file can load multiple mapping files, each corresponding to a table in the database.


3) Construct session factory: construct session factory SqlSessionFactory by MyBatis environment configuration information.


4) Create the session object: The session factory creates the SqlSession object, which contains all the methods for executing the SQL statement.


5) Executor Executor: MyBatis defines an Executor interface to operate the database. It dynamically generates SQL statements to be executed according to the parameters passed by SqlSession, and is responsible for the maintenance of query cache.


6) MappedStatement object: In the Executor interface execution method, there is a parameter of type MappedStatement. This parameter encapsulates the mapping information and stores the ID and parameters of the SQL statement to be mapped.


7) Input parameter mapping: Input parameter types can be set types such as Map and List, as well as basic data types and POJO types. The input parameter mapping procedure is similar to the JDBC procedure for setting parameters on a preparedStatement object.


8) Output result mapping: Output result types can be set types such as Map and List, as well as basic data types and POJO types. The output result mapping process is similar to the JDBC result set parsing process.


What is the functional architecture of MyBatis



We divide the functional architecture of Mybatis into three layers:


API Interface layer: Interface apis for external use by developers to manipulate the database through these native apis. As soon as the interface layer receives the call request, it calls the data processing layer to complete the specific data processing.

Data processing layer: responsible for specific SQL lookup, SQL parsing, SQL execution and execution result mapping processing, etc. Its main purpose is to complete a database operation based on the request of the call.

Base support layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading, and cache handling, all of which are common and extracted as the most basic components. It provides the most basic support for the upper data processing layer.





What Executor executors does Mybatis have?What’s the difference between them?

Mybatis has three basic Executor executors: SimpleExecutor, ReuseExecutor, and BatchExecutor.


SimpleExecutor: Every time an Update or select is performed, a Statement object is opened and the Statement object is closed immediately.


ReuseExecutor: If the Statement object exists, use it. If the Statement object does not exist, create it. After the Statement object is used, place it in Map<String, Statement> for next use. In short, the Statement object is reused.


BatchExecutor: Update (no SELECT, JDBC batch does not support SELECT), add all SQL to the batch (addBatch()), and wait for execution (executeBatch()), which caches multiple Statement objects. Each Statement object is addBatch() and waits for the executeBatch() batch to be executed one by one. Same as JDBC batch processing.


Scope: These Executor features are strictly limited to the SCOPE of the SqlSession lifecycle.


How to specify which Executor Executor to use in Mybatis?

In the Mybatis configuration file, you can specify the default ExecutorType ExecutorType in Settings, or manually pass the ExecutorType parameter to the SqlSession creation method of DefaultSqlSessionFactory. For example, SqlSession openSession(ExecutorType execType).


Configure the default actuator. SIMPLE is a plain actuator; The REUSE executor reuses prepared statements. The BATCH executor reuses statements and performs BATCH updates.


Does Mybatis support lazy loading?If so, how does it work?

Mybatis only supports lazy loading of association associative objects and collection associative objects. Association refers to one-to-one and collection refers to one-to-many queries. In Mybatis configuration file, you can configure whether to enable lazy-loading lazyLoadingEnabled = true | false.


The principle is that CGLIB is used to create a proxy object for the target object. When the target method is called, the interceptor method is entered, such as a.geb ().getName(). The interceptor invoke() method finds that A.geb () is null. A. setb (); a.getName (); a.getname (); a.getb (); a.getname (); This is the basic principle of lazy loading.


Of course, not only Mybatis, almost all including Hibernate, support lazy loading principle is the same.


mapper

The difference between #{} and ${}

#{} is a placeholder, precompiled for processing; ${} is a concatenation, string substitution, no precompilation processing.


#{} is a string that is passed as a parameter in Mybatis. Call the set method in PreparedStatement to assign the value.


{} is the value of a variable in Mybatis. {} is the value of a variable in Mybatis. {} is the value of a variable


After a variable is replaced, the corresponding variable is automatically quoted as’ ‘; ${} will not be quoted as’ ‘.


#{} can effectively prevent SQL injection, improve system security; ${} does not prevent SQL injection


#{} substitution is in the DBMS; The variable substitution for ${} is outside the DBMS

Public User selectUser(String name, int deptId); <select id="selectUser" resultMap="UserResultMap">    select * from user    where user_name = #{0} and dept_id = #{1}#{} This method is not recommended because the SQL layer is not intuitive and is prone to error once the order is adjusted. SelectUser (@param ("userName") String name, int @param ("deptId") deptId); #{} corresponds to the name in parentheses of @param annotation. This method is more intuitive in the case of few parameters and is recommended.Copy the code

How do I get the generated primary keyCopy the code

For databases that support primary key increment (MySQL)

<insert id="insertUser" useGeneratedKeys="true" keyProperty="userId" >    insert into user(     user_name, user_password, create_time)     values(#{userName}, #{userPassword} , #{createTime, jdbcType= TIMESTAMP})</insert>Copy the code

ParameterType can be left unwritten and Mybatis can infer the incoming data type. If you want to access primary keys, parameterType should be either a Java entity or a Map. This allows the data to be retrieved from the AVA entity or Map after insertion. Get the primary key by getUserId

Oracle database that does not support primary key increment

For data like Oracle, there is no primary key increment, but a sequential primary key increment is obtained.

You can use the < selectKey > tag to get the value of the primary key, both for databases that do not provide primary key increment and for databases that do

< selectKey > General usage

<selectKey keyColumn="id" resultType="long" keyProperty="id" order="BEFORE"></selectKey> Copy the code

How can YOU write a Mapper?

SqlSessionDaoSupport: To use this method, you need to write a mapper interface, mapper interface implementation class, mapper.xml file.


(1) Configure the mapper. XML location in sqlmapconfig. XML

<mappers>    <mapper resource="Address of mapper. XML file" />    <mapper resource="Address of mapper. XML file" /></mappers>Copy the code


(2) Define mapper interface


(3) Implement class integration SqlSessionDaoSupport


This.getsqlsession () can be used to add, delete, modify or query data in mapper.

(4) Spring configuration

<bean id="" class="Implementation of mapper Interface">    <property name="sqlSessionFactory"    ref="sqlSessionFactory"></property></bean>Copy the code

What is interface binding for MyBatis?What are the implementation methods?

Interface binding is to define any interface in MyBatis and bind the methods in the interface to SQL statements. We can call interface methods directly, so that we can have more flexible choices and Settings compared with the methods provided by SqlSession.

Interface binding can be implemented in two ways

By annotation binding, is in the interface method above the @SELECT, @update annotation, which contains Sql statements to bind;

In this case, to specify the namespace in the XML mapping file must be the full path name of the interface. When Sql statements are simple, annotations are used for binding. When Sql statements are complex, XML is used for binding. XML is often used for binding.


What are the requirements when using MyBatis mapper interface?

Mapper interface method name is the same as the ID of each SQL defined in mapper.xml.


The input parameter types for Mapper interface methods are the same as those for parameterType for 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 mapper. XML file is the classpath of Mapper interface.


As a best practice, an Xml mapping file is usually written with a Dao interface. How does this Dao interface work?Can methods in the Dao interface be overloaded if their parameters are different

Dao interface is also known as Mapper interface. The full 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 interface has no implementation class. When the interface method is called, the interface full name + method name concatenation string is used as the key value to uniquely locate an MappedStatement.

Example: com. Mybatis3. Mappers. StudentDao. FindStudentById,

Can only find the namespace for the com. Mybatis3. Mappers. StudentDao

MappedStatement with ID = findStudentById.

In Mybatis, each < SELECT >, < INSERT >, <update>, < DELETE > tag is parsed into an MappedStatement object.


Methods in the Dao interface cannot be overridden because of the save and find policy of the full name + method name.

The working principle of Dao interface is JDK dynamic proxy. Mybatis will use JDK dynamic proxy to generate proxy objects for Dao interface. Proxy object proxy intercepts interface methods, executes SQL represented by MappedStatement, and returns SQL execution results.


Dynamic SQL

What does Mybatis dynamic SQL do?What is the dynamic SQL?Can you briefly explain how dynamic SQL is executed?

Mybatis dynamic SQL allows us to write dynamic SQL in the form of tags in Xml mapping files, complete logical judgment and dynamic splicing SQL functions, Mybatis provides nine dynamic SQL tags trim | where | set | foreach | if | choose | s | otherwise | bind.


Its implementation principle is to use OGNL to calculate the value of the expression from the SQL parameter object, according to the value of the expression dynamic splicing SQL, to complete the function of dynamic SQL.


Plug-in modules

How does Mybatis paginate?How does paging plug-ins work?

Mybatis uses the RowBounds object for paging, which is memory paging for ResultSet result sets, rather than physical paging. You can write physical paging parameters directly in 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 a custom plug-in to intercept the SQL to be executed in the interception method of the plug-in, and then rewrite the SQL to add the corresponding physical paging statement and physical paging parameters according to the dialect.

Select t.* from (select * from student) t limit 0, 10

Brief introduction of Mybatis plug-in operation principle, and how to write a plug-in.

Only ParameterHandler, ResultSetHandler, StatementHandler, and Executor interfaces can be used as plugins in Mybatis. The interface method interception function is implemented by generating proxy objects for the interface to be intercepted. Each of the four methods of the interface object is invoked, specifically the Invoke () method of InvocationHandler, which, of course, only intercepts those methods that you specify to be intercepted.

Implementation of Mybatis Interceptor interface and autotype intercept () method, and then to the plug-in to write notes, specify which interface to intercept method which can, remember, don’t forget to you write a plug-in that is configured in the configuration file.


The cacheMybatis level 1, level 2 cache

1) Level 1 Cache: A HashMap local Cache based on PerpetualCache, which is stored at Session scope. When a Session is flushed or closed, all caches in that Session are cleared and Level 1 Cache is enabled by default.


2) The mechanism for tier 2 cache is the same as that for Tier 1 cache, which is PerpetualCache and HashMap by default. The difference is that the storage scope is Mapper(Namespace) and the storage source can be customized, such as Ehcache. Level 2 cache is not enabled by default. To enable level 2 cache, use the Level 2 cache attribute class to implement the Serializable interface (which can be used to store the state of objects). You can configure <cache/> in its mapping file.


If C/U/D has been applied to a select area (Session level 1 / Namespaces level 2), the cache will be cleared by default.

Sorted out some Java architecture, interview materials (micro-services, clusters, distributed, middleware, etc.), partners in need can pay attention to the public number [Java Cultivator], no routine to get