MyBatis FAQ summary

The deficiency of JDBC & mybatis solution The frequent creation and release of database connections cause a waste of...
if
where
set
foreach

The deficiency of JDBC & mybatis solution
  • The frequent creation and release of database connections cause a waste of system resources, which affects the system performance.
    • Solution: configure the data connection pool in mybatis-config.xml and use the connection pool to manage database connections.
  • SQL statements are written in the code, which makes the code difficult to maintain. The actual application of SQL may change greatly. SQL changes need to change the java code.
    • Solution: configure the Sql statement in the XXXXmapper.xml file and separate it from the java code.
  • It is troublesome to pass parameters to sql statements, because the where conditions of sql statements are not necessarily many or few. Placeholders need to correspond to parameters one by one.
    • Solution: Mybatis automatically maps java objects to sql statements.
  • 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.
    • Solution: Mybatis automatically maps sql execution results to java objects.
How to establish association between Dao interface in MyBatis and SQL of XML file
  • MyBatis encapsulates each SQL tag into a SqlSource object. Each SQL tag in the XML file corresponds to a MappedStatement object, in which two properties are very important:
    • ID: the ID composed of fully qualified class name + method name.
    • Sqlsource: the sqlsource object corresponding to the current SQL tag.
  • The working principle of Dao interface is JDK dynamic proxy. MyBatis runtime will use JDK dynamic proxy to generate proxy object for Dao interface. Proxy object proxy will intercept interface methods, execute the sql represented by MappedStatement, and then return the sql execution result.
    • Mapper interface has no implementation class. When calling interface methods, the interface fully qualified name + method name splicing string is used as the key value to uniquely locate a MappedStatement
For example, chestnuts: Interface method: com.mybatis3.mappers.StudentDao.findStudentById You will find: namespace by com.mybatis3.mappers.StudentDao Below id = findStudentById of MappedStatement
How does MyBatis encapsulate the sql execution result as a target object and return it? What are the mapping forms?

Method 1: use labels to define the mapping relationship between column names and object attribute names one by one

<resultMap type="com.pojo.User" id="myResult"> <id property="uid" column="uid"/> <result property="uName" column="uName"/> </resultMap> <select id="selectUser" resultMap="myResult"> select * from user </select>

Method 2: use the alias function of sql column to write the column alias as the object attribute name

<select id="selectUser" resultType="com.pojo.User"> select uid AS id, uName AS name from user </select>
  • resultMap is submitted manually and resultType is submitted automatically.
  • During the select mapping of MyBatis query, the return type can be either resultType or resultMap. resultType directly represents the return type, and resultMap is a reference to external resultMap, but resultType and resultMap cannot exist at the same time.
Dynamic sql for MyBatis

MyBatis dynamic sql allows us to write dynamic sql in the form of tags in the xml Mapping file to complete the functions of logical judgment and dynamic splicing of sql.

if

<if test="name!=null and name!=''"> e.emp_name = # </if>

where

Put sql into the where dynamic tag. When at least one condition is met, the where statement will be inserted and the and before the condition statement will be removed.

<where> <if test="name!=null and name!=''"> and e.emp_name=# </if> <if test="dep!=null"> and e.emp_dep=# </if> </where>

set

set can be used to dynamically include columns that need to be updated and discard other columns.

<update id="updateAuthorIfNecessary">update Author <set> <if test="username != null">username=#,</if> <if test="password != null">password=#,</if> </set> where id=# </update>

foreach

<select id="countByUserList" parameterType="list"> SELECT COUNT(*) FROM users WHERE user_id IN <foreach item="userList" collection="list" separator="," open="(" close=")" index=""> # </foreach> </select>
Differences between L1 cache and L2 cache in MyBatis

L1 cache is a SqlSession level cache: MyBatis supports caching. Only L1 cache is enabled by default.

The first level cache needs to construct sqlSession object when operating the database, and there is a data structure in the object to store cached data. Cache data areas between different sqlsessions do not affect each other. That is, it can only work in the same sqlSession, and the caches in different sqlsessions cannot be read from each other.

MyBatis L2 cache is mapper level cache, which can improve the efficiency of database query and application performance.

Multiple sqlsessions operate the sql statement of the same Mapper. Multiple sqlsessions can share the L2 cache, which is cross sqlsessions.

L2 cache startup method: add the following to mybatis.xml configuration file:

<span style="font-size:18px;"> <settings> <!--Enable L2 cache--> <setting name="cacheEnabled" value="true"/> </settings> </span>
Interface binding method in MyBatis
  • Bind through annotation: add @ Select, @ Update and other annotations to the interface methods, which contain Sql statements for binding (annotation binding is recommended when Sql statements are relatively simple)
  • Bind through xml file: specify the namespace in the xml Mapping file as the full pathname of the interface (xml binding is recommended when the SQL statement is complex)
The difference between MyBatis and Hibernate
  • MyBatis is not entirely an ORM framework, because MyBatis requires developers to write their own Sql statements.
  • MyBatis directly writes the original sql, which can strictly control the sql execution performance and has high flexibility. It is very suitable for software development with low requirements for relational data model, because the requirements of such software change frequently. However, the premise of flexibility is that MyBatis cannot be database independent. If you need to implement software that supports multiple databases, you need to customize multiple sets of sql mapping files, which is a heavy workload.
  • Hibernate has strong object / relational mapping ability and good database independence. For software with high requirements for relational model, if developed with hibernate, it can save a lot of code and improve efficiency.

4 October 2021, 16:23 | Views: 8119

Add new comment

For adding a comment, please log in
or create account

0 comments