Talking about: MyBatis framework learning (interview collection!!!)

Preface

In this article, I mainly share a few points that I think MyBtis is more important, or the analysis of several high-frequency questions of MyBatis in the interview. Good~
Not much nonsense, let's just start dry goods! ! !

1. Basic overview

1 Overview:

Anyone who has studied MyBatis knows that MyBatis can be said to be an enhanced version of JDBC. Since it is related to JDBC, everyone must know the role of MyBatis, and naturally it cannot be separated from the database.

MyBatis is a mainstream ORM framework, formerly called iBatis, and later renamed MyBatis, a framework for data persistence.

2. Advantages:

Since it is an enhanced version of JDBC, when we are learning JDBC, we can know that the amount of JDBC code is relatively large, and MyBatis encapsulates JDBC, which greatly reduces the amount of code

  • Greatly simplifies the development of JDBC code
  • Simple and easy to use, easy to use, with better flexibility
  • Reduce program coupling by defining SQL in XML
  • Support dynamic SQL, can realize functions flexibly according to specific business needs

3. Disadvantages:

Is MyBatis the best? Everything has its advantages, even optimized JDBC

  • Compared with Hibernate, developers need to complete more work, eg: define SQL, set the mapping relationship between POJO and data, etc.
  • Developers are required to have a certain SQL writing ability, and the workload is relatively large in some specific scenarios
  • The portability of the database is poor. SQL depends on the underlying database. If the database is migrated, part of the SQL needs to be rewritten

Second, the problem of environmental construction

For some friends who are just starting to learn MyBatis, setting up an environment can be a headache. Next, I will summarize the mistakes that you may make when setting up the environment and testing for the first time.

1. The configuration file is useless to register

2. Binding interface error

3. The method name is wrong

4. The return value type is incorrect

5. Maven export resource error

6.mysql is before 5.7. When registering the driver, it should be com.mysql.jdbc.Driver
and after mysql5.7 it is com.mysql.cj.jdbc.Driver

Three, CRUD considerations

When performing database operations: add, delete, modify, and commit transactions! ! !

There are two ways:
manual submission: sqlSession.commit(); method to submit the transaction
automatic submission:
we can manually set to true when we write the tool class

//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
    public static SqlSession getSqlSession(){
         return sqlSessionFactory.openSession(true);
    }

Four, configuration analysis

1. Environment and attributes

①environments:
MyBatis can be configured to adapt to multiple environments, but remember: Although multiple environments can be configured, each SqlSessionFactory instance can only choose one environment.

Mybatis's default transaction manager is JDBC

Connection pool: POOLED

②Properties:
We can use the properties property to achieve the reference configuration file

These attributes can be configured externally and can be dynamically replaced. You can configure these properties in a typical Java property file, or you can set [db.properties] in the sub-elements of the properties element

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

2. Common configuration

Next, let me tell you: Type aliases
Type aliases can set an abbreviated name for a Java type.
It is only used for XML configuration and is intended to reduce redundant writing of fully qualified class names. E.g:

<typeAliases>
        <typeAlias type="com.zjd.pojo.User" alias="User"/>
    </typeAliases>

Or use the package name:

Scan the package of the entity class, its default alias is the lowercase of the class name of this class

<typeAliases>
  <package name="com.zjd.pojo"/>
</typeAliases>

to sum up:

There are fewer entity classes, use the first method

If there are too many entity classes, you can use the second

But the first type can be aliased by diy

The second type can be aliased by adding annotations @Alias()

3. Mapper

When you ran the mybatis program for the first time, you must have seen this error: MapperRegistry
translated that means: we are not registered and bind our mapper file
at runtime, if we do not bind our corresponding interface in the core configuration file How can the program recognize the Mapper.xml?

method one:

<mappers>
    <mapper resource="com/wdit/dao/userMapper.xml"/>
</mappers>

Way two:

Use class file binding registration

<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mappers> 

important point:

  • The interface and its mapper configuration file must have the same name
  • The interface and its mapper configuration file must be in the same package

Way three:

<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

important point:

  • The interface and its mapper configuration file must have the same name
  • The interface and its mapper configuration file must be in the same package

4. Life cycle and scope

SqlSessionFactoryBuilder:

  • Once the SqlSessionFactory is created, it is no longer needed
  • Local variable

SqlSessionFactory:

  • To put it plainly, it can be understood as: database connection pool
  • Once the SqlSessionFactory is created, it should always exist during the running of the application, there is no reason to discard it or recreate another instance
  • Therefore, the best scope of SqlSessionFactory is the application scope
  • The easiest is to use singleton mode or static singleton mode.

SqlSession:

  • A request to connect to the connection pool!
  • It needs to be closed immediately after use up, otherwise the resources will be occupied
  • The instance of SqlSession is not thread-safe, so it cannot be shared, so its best scope is request or method scope
    Insert picture description here

5. Solve the problem of inconsistency between attribute names and field names

Sometimes, we will find that pwd is written in the database table, but when we create the entity class, it is written as password. As a result, we will report an error when testing. What should we do?

1. Method 1:

Alias

  select id,name,pwd as password from user where id= #{id}

2. Method two:

Use ResultMap result set mapping

<!--    结果集映射-->
    <resultMap id="UserMap" type="User">
<!-- column数据库中的字段,property实体类中的属性-->
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
    </resultMap>
    
    <select id="getUserByID" resultMap="UserMap">
        select * from mybatis.user where id= #{id}
    </select>
    

Six, many-to-one and one-to-many problems

Many-to-one and one-to-many questions are common questions in MyBatis, and they are also commonly asked by interviewers.
Insert picture description here
Here, I will briefly talk about the two methods of implementation:
① Nested queries according to the results -------- -------------->SQL statement is complete
②Follow the nested query of the query---------------------->Similar to sub Query, sql statement nested sql statement
Both methods are methods to solve the problem, and there is no superiority, but pay attention

  • Ensure the readability of sql [easy to understand]
  • Pay attention to the problem of one-to-many and many-to-one, attribute names and fields
  • The problem is not easy to eliminate, you can use the log

Seven, dynamic SQL

The so-called dynamic sql, we can understand that dynamically generating sql
dynamic sql according to different conditions is relatively easy to understand , here, I will mainly talk about sql fragments

<sql id="if-title-author">
    <if test="title != null">
        and title=#{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</sql>

When we write dynamic SQL, we find that the same code frequently appears. At this time, we can take the method of SQL fragments to extract the repeated

<include refid="if-title-author"></include>

In the subsequent SQL statement, insert the include tag to use, reducing the complexity of the code

Eight, cache

Here I mainly talk about the caching principle of MyBatis:
the order of user queries:
actually from right to left, that is, from the second level cache-the first level cache-to the database
Insert picture description here

Guess you like

Origin blog.csdn.net/zjdzka/article/details/113104528