Personally, this part of the source code is one of the important foundation is reflection, but here is not posted source code, learn Java reflection.

outline

MyBatis Interview FAQ

What is data persistence?

Data persistence is the general term for transforming a “data” model in “memory” into a “storage” model and a storage model into a data model in memory. For example, file storage, data reading and so on are data persistence operations. The data model can be any “model of a data structure or object, XML, binary stream,” etc. When we write an application to operate on a database and “add, delete, change, or query” table data, it is a data persistence operation.

Mybatis framework introduction

  • MyBatis framework is an open source data persistence layer framework.
  • It internally encapsulates database access via JDBC, supports plain SQL queries, stored procedures, and advanced mapping, and virtually eliminates all manual JDBC code and parameter Settings and result set retrieval.
  • MyBatis as a framework of persistence layer, its main idea is to strip out a large number of SQL statements in the program and configure them in the configuration file to achieve flexible configuration of SQL.
  • This has the advantage of separating the SQL from the program code, allowing you to modify the SQL directly in the configuration file without modifying the code.

What is ORM?

Object/Relational Mapping (ORM) is a data persistence technology. It “establishes a direct correspondence between the object model and the relational database” and provides a mechanism to “manipulate the data of database tables through JavaBean objects.” MyBatis is configured and mapped in a simple “XML” or “annotation” way. The mapping between entity classes and SQL statements is a “semi-automatic” ORM implementation (semi-automatic because we write our own SQL).

The advantages and disadvantages of MyBatis framework and its application occasions

advantages

  1. More than 50% less code than JDBC.
  2. MyBatis is an easy-to-learn persistence layer framework, compact and easy to learn.
  3. MyBatis is quite flexible, will not impose any impact on the existing design of the application or database, SQL written in XML files, completely separated from the program code, reduce the degree of coupling, easy to unified management and optimization, and reusable.
  4. XML tags are provided to support the writing of dynamic SQL to meet different business requirements.
  5. Provides mapping labels to support ORM field relational mapping of objects to databases.

disadvantages

  1. SQL statement writing workload is large, the ability of developers to write SQL has certain requirements.
  2. SQL statements depend on the database, so the database does not have good portability. Do not replace the database.

Applicable scenario

MyBatis focuses on SQL itself and is a flexible DAO layer solution. MyBatis is the best choice for projects with high performance requirements or variable requirements, such as Web projects.

What are the differences between MyBatis and Hibernate?

  1. Unlike Hibernate, Mybatis is not exactly an ORM framework because Mybatis requires programmers to write their own Sql statements.
  2. Mybatis directly write the original SQL, SQL execution performance can be strictly controlled, high flexibility, very suitable for the software development of the relational data model requirements are not high, because this kind of software needs to change frequently, but a demand change requires rapid output results. However, the premise of flexibility is that Mybatis cannot achieve database independence. If you need to implement software supporting a variety of databases, you need to customize multiple sets of SQL mapping files, and the workload is heavy.
  3. Hibernate object/relational mapping ability is strong, database independence is good, for software with high requirements of relational model, if Hibernate development can save a lot of code, improve efficiency.

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

  1. # {}It’s precompiled processing,The ${}It’s string substitution.
  2. Mybatis in dealing with# {}, will be in the SQL# {}Replace with? Call the set method in PreparedStatement to assign the value.
  3. Mybatis in dealing withThe ${}When means theThe ${}Replace it with the value of the variable.
  4. use# {}It can effectively prevent SQL injection and improve system security.

What if the attribute name in the entity class is different from the field name in the table?

  1. The first is to make the alias of the field name consistent with the attribute name of the entity class by defining the alias of the field name in the SQL statement of the query.
  2. Type 2: Pass<resultMap>To map the one-to-one correspondence between field names and entity class attribute names.

How to write fuzzy query like statement?

  1. Type 1: Add SQL wildcards to Java code.
  2. 2. Concatenate wildcards in SQL statements, which causes SQL injection

How does the Dao interface work? Can methods in the Dao interface be overloaded if their parameters are different?

Dao interfaces are Mapper interfaces. The full name of an interface is the value of namespace in the mapping file. The method name of the interface is the ID value of the Mapper Statement in the mapping file. The parameters in the interface method are the parameters passed to SQL. There is no implementation class for the Mapper interface. When an interface method is called, “the full name of the interface + the method name concatenated string serves as the key value” and “a MapperStatement can be uniquely located”. In Mybatis, each < SELECT >, < INSERT >,

, < DELETE > tag will be parsed into a MapperStatement object. Methods in the Mapper interface are “not overloadable” because they use the save and find strategy of the full name + method name. Mapper interface works by JDK dynamic proxy. Mybatis will use JDK dynamic proxy to generate proxy object for Mapper interface. The proxy object intercepts interface methods, executes THE SQL represented by MapperStatement, and returns the SQL execution result.

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

Mybatis uses the “RowBounds” object for paging, which is memory paging performed against ResultSet result sets rather than physical paging. Physical paging can be done by writing parameters with physical paging directly in SQL, or physical paging can be done using paging plug-ins. The basic principle of the paging plug-in is to use the “Mybatis provided plug-in interface” to implement a custom plug-in, in the “interception method to intercept the SQL to be executed”, then rewrite the SQL, according to the “dialect” to add the corresponding “physical page statement and physical page” parameters.

How does Mybatis encapsulate SQL execution results as target objects and return them? What are the mappings?

  1. The first is to use<resultMap>Tag that defines the mapping between database column names and object attribute names one by one.
  2. The second is to use the SQL column alias function to write the column alias as the object property name.

After having the mapping relationship between column name and attribute name, Mybatis creates objects through “reflection”, and uses “reflection to assign values to the attributes of the object and return them one by one”. Those attributes that cannot find the mapping relationship cannot complete the assignment.

What is Mybatis dynamic SQL? How does it work? What dynamic SQL is there?

Mybatis dynamic SQL can be prepared in the form of tags in Xml mapping files, the execution principle is “according to the value of the expression to complete the logical judgment and dynamic splicing SQL” function.

In the Xml mapping files of Mybatis, can the IDS of different Xml mapping files be repeated?

Different Xml mapping files, if configured with namespace, then the ID can be repeated; If no namespace is configured, the ID must be unique. Namespace + ID is used as the key of Map <String,MapperStatement>. If there is no namespace, only ids are left. Duplicate ids will overwrite each other. With a namespace, the natural ID can be repeated. With different namespaces, the namespace+ ID will naturally be different.

Mybatis semi-automatic ORM mapping tool What’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 “manually write SQL to complete” when querying associated objects or associated collection objects, so it is called “semi-automatic ORM mapping tool”.

How many ways can MyBatis implement one-to-one? How does it work?

There are joint query and nested query. Joint query is a joint query of several tables, which can be queried only once. It can be completed by configuring the Association node in the resultMap to configure one-to-one classes. In a nested query, you can first query a table, and then query data in another table based on the foreign key ID of the result in the table, again using association configuration, but the query in the other table using select attribute configuration.

MyBatis implements one to many in several ways, how to operate?

There are federated and nested queries. Joint query is a joint query of several tables, which is only queried once. It can be completed by configuring one-to-many classes in the Collection node in the resultMap. The nested query is to first query a table, according to the foreign key ID of the result in the table, to query data in another table, also through the configuration of collection, but the query of the other table through the select node configuration.

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. It works by using “CGLIB creates 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. Then “send the saved SQL query associated with the object B separately”, “query B up”, “then call a.setb (B)”, so that the object B property of A has a value, and then complete the a.geb ().getName() method call.

Mybatis level 1, level 2 cache

  • Level 1 Cache: A HashMap local Cache based on PerpetualCache, with storage scope of Session. When a Session is flushed or closed, all caches in that Session are cleared, enabling Level 1 Cache by default.
  • Level 2 caches have the same mechanism as Level 1 caches, with PerpetualCache and HashMap storage by default, but with Mapper(Namespace) storage scope and customizable storage source, such as Ehcache. Level 2 caching is not enabled by default. To enable level 2 caching, use the Level 2 cache attribute class to implement the Serializable interface (which can be used to store the state of objects), which can be configured in its mapping file.
  • If a C/U/D operation is performed on a Session (level 1) or Namespaces (level 2), all caches in the select area will be cleared by default.

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:

  • Annotation binding, is in the interface method above the @SELECT, @update annotation, which contains Sql statements to bind;
  • The other option is to bind by writing SQL in XML. 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?

  • The Mapper interface method name is the same as the ID of each SQL defined in mapper.xml;
  • The input parameter types for the Mapper interface methods are the same as those for each SQL parameterType defined in mapper.xml.
  • The output parameter type of the Mapper interface method is the same as the resultType type of each SQL defined in mapper.xml.
  • The namespace in the mapper. XML file is the class path of the Mapper interface.

How does Mybatis prevent SQL injection?

Let’s first look at the differences between the following two SQL statements:

<select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap">

select id, username, password, role

from user

where username = #{username,jdbcType=VARCHAR}

and password = #{password,jdbcType=VARCHAR}

</select>

Copy the code
<select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap">

select id, username, password, role

from user

where username = ${username,jdbcType=VARCHAR}

and password = ${password,jdbcType=VARCHAR}

</select>

Copy the code

# and $in mybatis

  • #Treat all incoming data as a string, and double quotes are placed around automatically passed data. Such as:where username=#{username}, if the value passed in is 111, then the value parsed into SQL iswhere username="111", if the value passed in is id, the SQL parsed into iswhere username="id".
  • $Display the incoming data directly in SQL. Such as:where username=${username}, if the value passed in is 111, then the value parsed into SQL iswhere username=111; If the value passed in is:drop table user;, the SQL parsed into is:select id, username, password, role from user where username=; drop table user;
  • #Can prevent SQL injection to a large extent,$Method does not prevent Sql injection.
  • $Method is generally used to pass in database objects, such as table names.
  • General use#Don’t use$, if necessary"${} XXX"Such parameters must be manually filtered to prevent SQL injection attacks.
  • In MyBatis,"${} XXX"Arguments in this format are directly involved in SQL compilation, thus preventing injection attacks. However, only dynamic table names and column names can be used"${} XXX"This parameter format. Therefore, such parameters need to be handled manually in the code to prevent injection.

SQL Injection:

“SQL injection”, everyone is familiar with, is a common attack. An “attacker” enters strange SQL snippets (such as “or ‘1’ = ‘1’”) on the form information or URL of the interface, potentially breaking into “under-validating” applications. So, we need to do some work in our application to protect against such attacks. In security-critical applications, such as banking software, it is common to prevent SQL injection by replacing all “SQL statements” with “stored procedures.” This is, of course, “a very safe way to do it,” but we probably don’t need this rigid way in normal development.

How does Mybatis prevent SQL injection

MyBatis framework as a semi-automatic persistence layer framework, its SQL statements have to be written manually by ourselves, this time of course need to prevent SQL injection. In fact, MyBatis SQL is a “input + output” function, similar to the structure of the function, refer to the above two examples. ParameterType indicates the input parameterType, resultType indicates the output parameterType. In response to the above, if we want to prevent SQL injection, it makes sense to work on input parameters. In the above code, # is used to concatenate the input parameters in THE SQL. After passing in the parameters, print the executed SQL statement, and the SQL will look like this:

select id, username, password.role from user where username=? and password=?

Copy the code

No matter what parameters you enter, the printed SQL looks like this. This is because MyBatis has enabled the precompilation function, before SQL execution, the above SQL will be sent to the database for compilation; To execute, directly replace the placeholder “? “with the compiled SQL. That’s it. Since SQL injection only works with the compile process, this approach is a good way to avoid SQL injection problems.

How does MyBatis achieve SQL precompilation? Underneath the framework, PreparedStatement is the JDBC PreparedStatement class. PreparedStatement is a subclass of the familiar Statement, whose object contains compiled SQL statements. This “ready to go” approach not only improves security, but also improves efficiency when executing the same SQL multiple times. The reason is that the SQL is already compiled and does not need to be compiled when it is executed again.

// Secure, precompiled

Connection conn = getConn();// Get the connection

String sql = "select id, username, password, role from user where id=?"// The statement is precompiled before the SQL is executed

PreparedStatement pstmt = conn.prepareStatement(sql); 

pstmt.setString(1, id); 

ResultSet rs=pstmt.executeUpdate(); 

.

Copy the code
// Insecure, not precompiled

private String getNameByUserId(String userId) {

    Connection conn = getConn();// Get the connection

    String sql = "select id,username,password,role from user where id=" + id;

    // When id is "3; drop table user;" The following SQL statement is executed:

    //select id,username,password,role from user where id=3; drop table user;

    PreparedStatement pstmt =  conn.prepareStatement(sql);

    ResultSet rs=pstmt.executeUpdate();

.

}

Copy the code

“Conclusion” :

#{} : is equivalent to a PreparedStatement in JDBC

${} : is the value of the output variable

In short, #{} is precompiled and safe; ${} is not precompiled, just takes the value of a variable, is not secure, SQL injection exists.

Creation is not easy, if you think it will help, give a small star. Making address 😁 😁 😁

This article is formatted using MDNICE