Mybatis_ study notes

1 Introduction

Mybatis: Persistence layer framework (sql mapping framework) that interacts with the database;
before mybatis, the original database operations have jdbc — dbUtils(QueryRunner) — JdbcTemplate —; these tools are too troublesome, and sql is hard-coded
Insert picture description here

2. Environment setup

2.1 Create a java project

2.2 Create security test library, test table, and javabean to encapsulate data, and dao interface to operate database

2.3 Operate the database with mybatis

2.3.1 Guide package

mysql-connector-java-5.1.37-bin.jar
mybatis-3.4.1.jar
log4j-1.2.17.jar

2.3.2 Write configuration

  1. The first configuration file-global configuration file: (called the global configuration file of mybatis, which guides how to run mybatis correctly, such as which database to connect to)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <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>
  <!--引入我们自己编写的每一个接口的实现文件-->
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>
  1. The second configuration file-sql mapping file: (How to write each method how to send sql statement to the database, how to execute... equivalent to the implementation class of the interface)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>
  1. The implementation file of the dao interface we wrote above is unknown to mybatis by default.需要在全局的配置文件中注册
 <!--引入我们自己编写的每一个接口的实现文件-->
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>

note:

The parameterType can never be written
. There is no need to write the return value type in the SQL that adds, deletes, and changes--how many rows are affected by the addition, deletion, and modification; if it returns a boolean (affecting 0 rows, it returns false)

2.3.3 Test

  1. Get the SqlSessionFactory object first according to the global configuration file
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  1. Get the SQLSession object (equivalent to obtaining a connection before)
SQLSession openSession = sqlSessionFactory.openSession();
  1. Get the implementation of the dao interface through the current session (mapper)
EmployeeDao dao = openSession.getMapper(EmployeeDao.class);
//try{
    
    
	dao.xxxById();   //调用查询方法
 }finally{
    
    
 	//跟新数据库时必须commit,否则不生效(查询方法可以不用);也可在创建session时传入true参数代表自动提交: SQLSession openSession = sqlSessionFactory.openSession(true);
 	//openSession.commit();  
	openSession.closs();
 }

3. Two configuration files of mybatis

3.1 Global configuration file

mybatis-config.xml: some global configuration to guide mybatis to run correctly
Properties in the global configuration file:

3.2 sql mapping file

EmployeeDao.xml: equivalent to an implementation description of the dao interface

Obtain the implementation of the dao interface through the session EmployeeDao dao = openSession.getMapper(EmployeeDao.class);: what is obtained is the proxy object of the interface (automatically created by mybatis).
SqlSessionFactory creates the SQLSession object, and the factory only needs to be new once.
SqlSession: It is equivalent to the interaction between the connection and the database, and a session with the database. A new sqlSessin should be created every time;

3.2.1 Tags in the sql mapping file

  1. cache, cache-ref: related to cache

  2. delete ,insert , selete , update

  3. parameterMap: parameter map, (obsolete)... originally it was used for complex parameter mapping

  4. resultMap: result mapping: custom result set encapsulation rules

    Customize the mapping rules for each column of data and javaBean
    type=" ": specify which javaBean custom encapsulation rule; full class name
    id=" ": unique identifier: let the alias refer to the back
    Primary key column: <id property="id" column="id"/>
    column=" in the primary key column ": Specify which column is the primary key
    . Property=" "in the primary key column: Specify which attribute of cat encapsulates a type of id. The
    Insert picture description here
    result set contains the wording of the object
    Insert picture description here
    or
    Insert picture description here
    contains the collection
    Insert picture description here

  5. sql: extract reusable sql

3.2.1.1 delete,update,insert

Insert picture description here

4. The difference between # and $ in mybatis

In mybatis, there are two ways to get the value:
#(attribute name): It is the way of parameter precompilation, the position of the parameter is replaced with?, the parameters are later precompiled settings, safe, no SQL injection;
${property name}: It is not parameter precompilation, but is directly combined with the sql statement; it is not safe; but it can dynamically obtain the table name;

5. Dynamic SQL

5.1. <where>

5.2. <if>

5.3. <trim>

trim: intercept the string:
prefix=" ": prefix: add a prefix to the
entire SQL below prefixOverrides="": remove the extra characters in front of the entire string
suffix=" ": add a suffix to the whole;
suffixOverrides="" : Which of the latter is too much can be removed

5.4. <foreach>

foreach: used to traverse the collection
The attributes in the collection are:

collection="": Specify the key of the collection to be traversed, generally you can specify list, map and other types

  • Note: When customizing the type at that time, this value is not the variable name of the formal parameter, and the @Paramspecified name is used in the interface

close="": What ends with
index="": Index:

  • If the traversal is one list, index indicates that the specified variable saves the current index item;: saves the value of the current traversed element
  • If the traversal is one map, index: The specified variable is the key that saves the currently traversed element, and item: is the value of the current traversed element

item="variable name": start with a variable name for each traversed element for easy reference
open="": start with what
separator="": separator of each traversed element

5.5 <choosebranch selection label

6. Cache Mechanism

Mybatis caching mechanism: Map; can save some of the data that is queried;
first-level cache: thread-level cache; local cache; SqlSession-level cache;
second-level cache: global cache; in addition to the current thread; SqlSession can use other things can use;

6.1. Level 1 cache

6.1.1. The first level cache of mybatis (SqlSession level cache), which exists by default;

As long as the data previously queried, mybatis will be saved in the first level cache (Map) by default; the next time it is retrieved, it will be taken directly from the cache;

6.1.2. Several cases of first-level cache invalidation

  1. Different SqlSession
  2. Same method, different parameters
  3. Perform any addition, deletion and modification operation during the same SqlSession, the addition, deletion and modification will empty the cache;
  4. Manually clear the cache openSession.clearCache();

6.2. Second level cache

The first level cache, after SqlSession is closed or submitted, the data of the first level cache will be placed in the second level cache;

6.2.1. Turn on the second-level cache

Mybatis does not turn on the second-level cache by default;

  1. Open in the global configuration file
<settings>
        <!--开启全局缓存开关-->
        <setting name="cacheEnabled" value="true"/>
 </settings>
  1. In the sql mapping file (xxxDao.xml), let it use the second level cache
<!-- 使用二级缓存-->
<cache></cache>
  1. Don't forget to serialize

6.2.2.

  1. There will not be the same data in the first level cache and the second level cache
  • In the second-level cache: the first-level cache is closed when it is closed;
  • In the first-level cache: if there is no secondary data in the second-level cache, it will look at the first-level cache, and the database will be checked if the first-level cache is not; the results of the database query are placed in the first-level cache;
  1. At any time, look at the second-level cache first, then the first-level cache, if you don't have one, go to the database;

6.3 Cache related settings

  1. Global setting cacheEnable: The switch to configure the second-level cache. The first-level cache is always on;
  2. useCacheAttributes of the select tag : Configure whether to use the second-level cache for this select. The first-level cache is always used;
  3. The flushCacheattributes of the sql tag : add, delete, and modify the default flushCache=true. After sql is executed, the first and second caches will be cleared at the same time. Query default flushCache=false.
  4. sqlSession.clearCache(): Only used to clear the first level cache.
  5. When a C/U/D operation is performed in a certain scope (first-level cache Session/second-level cache NameSpace), all caches in select under this scope will be cleared by default.

7. Integrate third-party cache

4. The four major components of mybatis

4.1 Executor

Executor: execute sql

4.2 ParameterHandler

Parameter processor: it will call typeHandlers(type processor) to perform parameter conversion

4.3. ResultSetHandler

Result set processor: Responsible for encapsulating the query result set into a specified object

4.4. StatementHandler

Guess you like

Origin blog.csdn.net/qq_40084325/article/details/112426277