MyBatis Study Notes

MyBatis was originally an open-source Apache project called iBatis. In June 2010, the project moved from the Apache Software Foundation to Google Code. After the development team moved to Google Code, iBatis 3.x was officially renamed MyBatis. The code was migrated to GitHub in November 2013. The name iBatis is a combination of “internet” and “abatis.” It is a Java-based persistence layer framework. The persistence framework provided by iBatis includes SQL Maps and Data Access Objects (DAO).

Contents

Introduction to MyBatis

History of MyBatis

  • MyBatis was originally an open-source Apache project called iBatis. In June 2010, the project moved from the Apache Software Foundation to Google Code. After the development team moved to Google Code, iBatis 3.x was officially renamed MyBatis. The code was moved to GitHub in November 2013.
  • The name iBatis comes from a combination of “internet” and “abatis.” It is a Java-based persistence framework. The persistence frameworks provided by iBatis include SQL Maps and Data Access Objects (DAO).

MyBatis Features

  1. MyBatis is an excellent persistence framework that supports customized SQL, stored procedures, and advanced mappings.
  2. MyBatis avoids almost all JDBC code, as well as manually setting parameters and retrieving result sets.
  3. MyBatis can use simple XML or annotations for configuration and object-relational mapping, mapping interfaces and Java POJOs (Plain Old Java Objects) to records in a database.
  4. MyBatis is a semi-automatic ORM (Object Relational Mapping) framework.

Download MyBatis

Comparison with Other Persistence Technologies

  • JDBC
    • SQL is embedded in Java code, resulting in tight coupling and the drawbacks of hard coding.
    • Maintenance is difficult, and SQL often needs to be changed to meet actual development requirements.
    • The code is verbose, resulting in low development efficiency.
  • Hibernate and JPA
    • Easy to use, with high development efficiency.
    • Long, complex SQL statements in the program may require bypassing the framework.
    • SQL generated automatically behind the scenes is difficult to optimize for special cases.
    • With a fully automatic framework based on full mapping, partially mapping POJOs with many fields is relatively difficult.
    • Excessive use of reflection leads to reduced database performance.
  • MyBatis
    • Lightweight, with excellent performance.
    • SQL and Java code are separate, with clearly defined responsibilities. Java code focuses on business logic, while SQL statements focus on data.
    • Development efficiency is slightly lower than Hibernate, but entirely acceptable.

Setting Up MyBatis

Development Environment

  • IDE: IntelliJ IDEA 2019.2
  • Build tool: Maven 3.5.4
  • MySQL version: MySQL 5.7
  • MyBatis version: MyBatis 3.5.7

Creating a Maven Project

  • Packaging type: jar

  • Add dependencies

    <dependencies>
        <!-- Mybatis核心 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!-- junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.3</version>
            </dependency>
    </dependencies>
    

Create the MyBatis Core Configuration File

It is conventionally named mybatis-config.xml. This filename is only a suggestion, not a requirement. Once Spring is integrated later, this configuration file can be omitted, so you can simply copy and paste the examples as you work.
The core configuration file is mainly used to configure the database connection environment and MyBatis global settings.
The core configuration file is stored in the src/main/resources directory.

<?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="com.mysql.cj.jdbc.Driver"/>  
                <property name="url" value="jdbc:mysql://localhost:3306/MyBatis"/>  
                <property name="username" value="root"/>  
                <property name="password" value="123456"/>  
            </dataSource>  
        </environment>  
    </environments>  
    <!--引入映射文件-->  
    <mappers>  
        <mapper resource="mappers/UserMapper.xml"/>  
    </mappers>  
</configuration>

Create a Mapper Interface

A mapper interface in MyBatis is equivalent to a DAO in the past. The difference is that a mapper is only an interface, so we don’t need to provide an implementation class.

package com.atguigu.mybatis.mapper;  
  
public interface UserMapper {  
    /**  
    * 添加用户信息  
    */  
    int insertUser();  
}

Creating a MyBatis Mapping File

  • Related concept: ORM (Object Relationship Mapping).
    • Object: Java entity class object
    • Relationship: relational database
    • Mapping: the correspondence between the two
Java Concept Database Concept
Class Table
Property Field/column
Object Record/row
  • Naming rules for mapping files
    • Use the name of the entity class corresponding to the table, followed by Mapper.xml.
    • For example, for table t_user, if the mapped entity class is User, the corresponding mapping file is UserMapper.xml.
    • Therefore, each mapping file corresponds to one entity class and the operations on one table.
    • MyBatis mapping files are used to write SQL and access and manipulate data in tables.
    • MyBatis mapping files are stored in the src/main/resources/mappers directory.
  • MyBatis supports operating on data through interfaces. The following two must match:
    • The fully qualified name of the mapper interface must match the mapping file's namespace (namespace).
    • A method name in the mapper interface must match the id attribute of the tag containing the SQL in the mapping file.
<?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="com.atguigu.mybatis.mapper.UserMapper">  
    <!--int insertUser();-->  
    <insert id="insertUser">  
        insert into t_user values(null,'张三','123',23,'女')  
    </insert>  
</mapper>

Testing Functionality with JUnit

  • SqlSession: Represents a session between a Java program and a database. (HttpSession is a session between a Java program and a browser.)
  • SqlSessionFactory: A “factory” that “produces” SqlSession instances.
  • Factory pattern: If the process for creating a particular object is basically fixed, we can encapsulate the code related to creating that object in a “factory class.” From then on, we can use this factory class to “produce” the objects we need.
public class UserMapperTest {
    @Test
    public void testInsertUser() throws IOException {
        //读取MyBatis的核心配置文件
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        //获取SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory,生产SqlSession对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        //获取sqlSession,此时通过SqlSession对象所操作的sql都必须手动提交或回滚事务
        //SqlSession sqlSession = sqlSessionFactory.openSession();
        //创建SqlSession对象,此时通过SqlSession对象所操作的sql都会自动提交  
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //通过代理模式创建UserMapper接口的代理实现类对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //调用UserMapper接口中的方法,就可以根据UserMapper的全类名匹配元素文件,通过调用的方法名匹配映射文件中的SQL标签,并执行标签中的SQL语句
        int result = userMapper.insertUser();
        //提交事务
        //sqlSession.commit();
        System.out.println("result:" + result);
    }
}
  • At this point, you need to commit the transaction manually. To commit transactions automatically, use SqlSession sqlSession = sqlSessionFactory.openSession(true); when obtaining the sqlSession object and pass in a Boolean parameter with the value true.

Add log4j Logging

  1. Add the dependency
    <!-- log4j日志 -->
    <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
    </dependency>
    
  2. Add the log4j configuration file
    • Name the log4j configuration file log4j.xml and place it in the src/main/resources directory.
    • Log levels: FATAL (fatal) > ERROR (error) > WARN (warning) > INFO (information) > DEBUG (debugging). The amount of detail in the output increases from left to right.
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
        <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
            <param name="Encoding" value="UTF-8" />
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
            </layout>
        </appender>
        <logger name="java.sql">
            <level value="debug" />
        </logger>
        <logger name="org.apache.ibatis">
            <level value="info" />
        </logger>
        <root>
            <level value="debug" />
            <appender-ref ref="STDOUT" />
        </root>
    </log4j:configuration>
    

Detailed Explanation of the Core Configuration File

The tags in the core configuration file must appear in a fixed order (some tags may be omitted, but the order must not be changed):
properties, settings, typeAliases, typeHandlers, objectFactory, objectWrapperFactory, reflectorFactory, plugins, environments, databaseIdProvider, mappers

<?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>
    <!--引入properties文件,此时就可以${属性名}的方式访问属性值-->
    <properties resource="jdbc.properties"></properties>
    <settings>
        <!--将表中字段的下划线自动转换为驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>
    <typeAliases>
        <!--
        typeAlias:设置某个具体的类型的别名
        属性:
        type:需要设置别名的类型的全类名
        alias:设置此类型的别名,且别名不区分大小写。若不设置此属性,该类型拥有默认的别名,即类名
        -->
        <!--<typeAlias type="com.atguigu.mybatis.bean.User"></typeAlias>-->
        <!--<typeAlias type="com.atguigu.mybatis.bean.User" alias="user">
        </typeAlias>-->
        <!--以包为单位,设置改包下所有的类型都拥有默认的别名,即类名且不区分大小写-->
        <package name="com.atguigu.mybatis.bean"/>
    </typeAliases>
    <!--
    environments:设置多个连接数据库的环境
    属性:
        default:设置默认使用的环境的id
    -->
    <environments default="mysql_test">
        <!--
        environment:设置具体的连接数据库的环境信息
        属性:
            id:设置环境的唯一标识,可通过environments标签中的default设置某一个环境的id,表示默认使用的环境
        -->
        <environment id="mysql_test">
            <!--
            transactionManager:设置事务管理方式
            属性:
                type:设置事务管理方式,type="JDBC|MANAGED"
                type="JDBC":设置当前环境的事务管理都必须手动处理
                type="MANAGED":设置事务被管理,例如spring中的AOP
            -->
            <transactionManager type="JDBC"/>
            <!--
            dataSource:设置数据源
            属性:
                type:设置数据源的类型,type="POOLED|UNPOOLED|JNDI"
                type="POOLED":使用数据库连接池,即会将创建的连接进行缓存,下次使用可以从缓存中直接获取,不需要重新创建
                type="UNPOOLED":不使用数据库连接池,即每次使用连接都需要重新创建
                type="JNDI":调用上下文中的数据源
            -->
            <dataSource type="POOLED">
                <!--设置驱动类的全类名-->
                <property name="driver" value="${jdbc.driver}"/>
                <!--设置连接数据库的连接地址-->
                <property name="url" value="${jdbc.url}"/>
                <!--设置连接数据库的用户名-->
                <property name="username" value="${jdbc.username}"/>
                <!--设置连接数据库的密码-->
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入映射文件-->
    <mappers>
        <!-- <mapper resource="UserMapper.xml"/> -->
        <!--
        以包为单位,将包下所有的映射文件引入核心配置文件
        注意:
            1. 此方式必须保证mapper接口和mapper映射文件必须在相同的包下
            2. mapper接口要和mapper映射文件的名字一致
        -->
        <package name="com.atguigu.mybatis.mapper"/>
    </mappers>
</configuration>

Default Type Aliases

<table><thead><tr><th>Alias</th><th>Mapped Type</th></tr></thead><tbody><tr><td>_byte</td><td>byte</td></tr><tr><td>_long</td><td>long</td></tr><tr><td>_short</td><td>short</td></tr><tr><td><font color="red">_int</font></td><td><font color="red">intZXQXZ</font></td></tr><tr><td><font color="red">_integerZXQXZ</font></td><td><font color="red">intZXQXZ</font></td></tr><tr><td>_doubleZXQXZ<td>doubleZXQXZ</tr><tr><td>_floatZXQXZ<td>floatZXQXZ</tr><tr><td>_booleanZXQXZ<td>booleanZXQXZ</tr><tr><td>stringZXQXZ<td>StringZXQXZ</tr><tr><td>byteZXQXZ<td>ByteZXQXZ</tr><tr><td>longZXQXZ<td>LongZXQXZ</tr><tr><td>shortZXQXZ<td>ShortZXQXZ</tr><tr><td><font color="red">intZXQXZ</td><td><font color="red">IntegerZXQXZ</td></tr><tr><td>integerZXQXZ<td>IntegerZXQXZ</tr><tr><td>doubleZXQXZ<td>DoubleZXQXZ</tr><tr><td>floatZXQXZ<td>FloatZXQXZ</tr><tr><td>booleanZXQXZ<td>BooleanZXQXZ</tr><tr><td>dateZXQXZ<td>DateZXQXZ</tr><tr><td>decimalZXQXZ<td>BigDecimalZXQXZ</tr><tr><td>bigdecimalZXQXZ<td>BigDecimalZXQXZ</tr><tr><td>objectZXQXZ<td>ObjectZXQXZ</tr><tr><td>mapZXQXZ<td>MapZXQXZ</tr><tr><td>hashmapZXQXZ<td>HashMapZXQXZ</tr><tr><td>listZXQXZ<td>ListZXQXZ</tr><tr><td>arraylistZXQXZ<td>ArrayListZXQXZ</tr><tr><td>collectionZXQXZ<td>CollectionZXQXZ</tr><tr><td>iteratorZXQXZ<td>IteratorZXQXZ</tr></tbody></table>

MyBatis CRUD Operations

  1. Add
    <!--int insertUser();-->
    <insert id="insertUser">
        insert into t_user values(null,'admin','123456',23,'男','[email protected]')
    </insert>
    
  2. Delete
    <!--int deleteUser();-->
    <delete id="deleteUser">
        delete from t_user where id = 6
    </delete>
    
  3. Modification
    <!--int updateUser();-->
    <update id="updateUser">
        update t_user set username = '张三' where id = 5
    </update>
    
  4. Query an Entity Object
    <!--User getUserById();-->  
    <select id="getUserById" resultType="com.atguigu.mybatis.bean.User">  
        select * from t_user where id = 2  
    </select>
    
  5. Query Set
    <!--List<User> getUserList();-->
    <select id="getUserList" resultType="com.atguigu.mybatis.bean.User">
        select * from t_user
    </select>
    
  • Notes:

    1. The select tag must have either the resultType or resultMap attribute to define the mapping between the entity class and the database table.
      • resultType: Automatic mapping, used when property names match column names in the table.
      • resultMap: Custom mapping, used for one-to-many or many-to-one relationships, or when column names and property names do not match.
    2. When a query returns multiple records, you cannot use an entity class as the return value; you must use a collection, or a TooManyResultsException will be thrown. If the query returns only one record, however, you can use either an entity class or a collection as the return value.

Two Ways MyBatis Retrieves Parameter Values (Important)

  • MyBatis has two ways to retrieve parameter values: ${} and #{}.
  • ${} performs string concatenation, while #{} assigns values using placeholders.
  • ${} builds SQL through string concatenation. When assigning a value to a string or date field, you must manually add single quotation marks. By contrast, #{} builds SQL by assigning values through placeholders, so single quotation marks are added automatically when assigning a value to a string or date field.

Parameters of a Single Literal Type

  • If a mapper interface method has a single literal-type parameter, you can use ${} and #{} with any name (preferably one that clearly describes the value) to retrieve the parameter value. Note that with ${}, you must manually add single quotation marks.
<!--User getUserByUsername(String username);-->
<select id="getUserByUsername" resultType="User">
    select * from t_user where username = #{username}
</select>
<!--User getUserByUsername(String username);-->
<select id="getUserByUsername" resultType="User">  
    select * from t_user where username = '${username}'  
</select>

Parameters with Multiple Literal Values

  • When a method in a mapper interface has multiple parameters, MyBatis automatically places them in a map.

    1. The keys are arg0, arg1, and so on, and the values are the corresponding parameters;
    2. The keys are param1, param2, and so on, and the values are the corresponding parameters.
  • You can access the corresponding values by using ${} and #{} with the map keys. Note that ${} requires manually adding single quotes.

  • You can use either arg or param. Note that arg starts at arg0, while param starts at param1.

<!--User checkLogin(String username,String password);-->
<select id="checkLogin" resultType="User">  
    select * from t_user where username = #{arg0} and password = #{arg1}  
</select>
<!--User checkLogin(String username,String password);-->
<select id="checkLogin" resultType="User">
    select * from t_user where username = '${param1}' and password = '${param2}'
</select>

Parameters of the Map Collection Type

  • If a method in a mapper interface requires multiple parameters, you can manually create a map collection and put the data in it. Then, you can access the map’s keys using ${} and #{} to retrieve the corresponding values. Note that you need to manually add single quotes when using ${}.
<!--User checkLoginByMap(Map<String,Object> map);-->
<select id="checkLoginByMap" resultType="User">
    select * from t_user where username = #{username} and password = #{password}
</select>
@Test
public void checkLoginByMap() {
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
    Map<String,Object> map = new HashMap<>();
    map.put("usermane","admin");
    map.put("password","123456");
    User user = mapper.checkLoginByMap(map);
    System.out.println(user);
}

Parameters of Entity Class Types

  • If a method parameter in a mapper interface is an entity class object, you can use both ${} and #{} to access property values by using the entity object's property names. Note that ${} requires you to manually add single quotes.
<!--int insertUser(User user);-->
<insert id="insertUser">
    insert into t_user values(null,#{username},#{password},#{age},#{sex},#{email})
</insert>
@Test
public void insertUser() {
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
    User user = new User(null,"Tom","123456",12,"男","[email protected]");
    mapper.insertUser(user);
}

Identifying Parameters with @Param

  • You can use the @Param annotation to identify method parameters in a mapper interface. These parameters are then placed in a map collection:

    1. The value of the @Param annotation’s value attribute is used as the key, and the parameter is used as the value;
    2. param1, param2, ... are used as keys, and the parameters are used as values.
  • You can access the keys in the map collection using \${} and #{} to retrieve the corresponding values. Note that ${} requires you to add single quotes manually.

<!--User CheckLoginByParam(@Param("username") String username, @Param("password") String password);-->
    <select id="CheckLoginByParam" resultType="User">
        select * from t_user where username = #{username} and password = #{password}
    </select>
@Test
public void checkLoginByParam() {
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
    mapper.CheckLoginByParam("admin","123456");
}

Summary

  • It is recommended to handle the two cases separately:

    1. Parameters of an entity class type
    2. Parameters annotated with @Param

MyBatis Query Features

  1. If the query returns only one row, it can be received using:
    1. An entity class object
    2. A List collection
    3. A Map collection; the result is {password=123456, sex=男, id=1, age=23, username=admin}
  2. If the query returns multiple rows, they must not be received using an entity class object, or a TooManyResultsException will be thrown. They can be received using:
    1. A List collection of entity class types
    2. A List collection of Map types
    3. Adding the @MapKey annotation to the mapper interface method

Querying a Single Entity Object

/**
 * 根据用户id查询用户信息
 * @param id
 * @return
 */
User getUserById(@Param("id") int id);
<!--User getUserById(@Param("id") int id);-->
<select id="getUserById" resultType="User">
    select * from t_user where id = #{id}
</select>

Query a List Collection

/**
 * 查询所有用户信息
 * @return
 */
List<User> getUserList();
<!--List<User> getUserList();-->
<select id="getUserList" resultType="User">
    select * from t_user
</select>

Query a Single Data Item

/**  
 * 查询用户的总记录数  
 * @return  
 * 在MyBatis中,对于Java中常用的类型都设置了类型别名  
 * 例如:java.lang.Integer-->int|integer  
 * 例如:int-->_int|_integer  
 * 例如:Map-->map,List-->list  
 */  
int getCount();
<!--int getCount();-->
<select id="getCount" resultType="_integer">
    select count(id) from t_user
</select>

Query a Single Record as a Map Collection

/**  
 * 根据用户id查询用户信息为map集合  
 * @param id  
 * @return  
 */  
Map<String, Object> getUserToMap(@Param("id") int id);
<!--Map<String, Object> getUserToMap(@Param("id") int id);-->
<select id="getUserToMap" resultType="map">
    select * from t_user where id = #{id}
</select>
<!--结果:{password=123456, sex=男, id=1, age=23, username=admin}-->

Query Multiple Records into a Map Collection

Method 1

/**  
 * 查询所有用户信息为map集合  
 * @return  
 * 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此时可以将这些map放在一个list集合中获取  
 */  
List<Map<String, Object>> getAllUserToMap();
<!--Map<String, Object> getAllUserToMap();-->  
<select id="getAllUserToMap" resultType="map">  
    select * from t_user  
</select>
<!--
    结果:
    [{password=123456, sex=男, id=1, age=23, username=admin},
    {password=123456, sex=男, id=2, age=23, username=张三},
    {password=123456, sex=男, id=3, age=23, username=张三}]
-->

Method Two

/**
 * 查询所有用户信息为map集合
 * @return
 * 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,并且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的map集合
 */
@MapKey("id")
Map<String, Object> getAllUserToMap();
<!--Map<String, Object> getAllUserToMap();-->
<select id="getAllUserToMap" resultType="map">
    select * from t_user
</select>
<!--
    结果:
    {
    1={password=123456, sex=男, id=1, age=23, username=admin},
    2={password=123456, sex=男, id=2, age=23, username=张三},
    3={password=123456, sex=男, id=3, age=23, username=张三}
    }
-->

Execution of Special SQL

Fuzzy Queries

/**
 * 根据用户名进行模糊查询
 * @param username 
 * @return java.util.List<com.atguigu.mybatis.pojo.User>
 * @date 2022/2/26 21:56
 */
List<User> getUserByLike(@Param("username") String username);
<!--List<User> getUserByLike(@Param("username") String username);-->
<select id="getUserByLike" resultType="User">
    <!--select * from t_user where username like '%${mohu}%'-->  
    <!--select * from t_user where username like concat('%',#{mohu},'%')-->  
    select * from t_user where username like "%"#{mohu}"%"
</select>
  • Among them, select * from t_user where username like "%"#{mohu}"%" is the most commonly used.

Batch Deletion

  • You can only use ${}. If you use #{}, the parsed SQL statement will be delete from t_user where id in ('1,2,3'). This treats 1,2,3 as a whole, so only the record with id 1,2,3 will be deleted. The correct statement should be delete from t_user where id in (1,2,3) or delete from t_user where id in ('1','2','3').
/**
 * 根据id批量删除
 * @param ids 
 * @return int
 * @date 2022/2/26 22:06
 */
int deleteMore(@Param("ids") String ids);
<delete id="deleteMore">
    delete from t_user where id in (${ids})
</delete>
//测试类
@Test
public void deleteMore() {
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
    int result = mapper.deleteMore("1,2,3,8");
    System.out.println(result);
}

Dynamically Setting Table Names

  • Only ${} can be used, because table names cannot be enclosed in single quotes.
/**
 * 查询指定表中的数据
 * @param tableName 
 * @return java.util.List<com.atguigu.mybatis.pojo.User>
 * @date 2022/2/27 14:41
 */
List<User> getUserByTable(@Param("tableName") String tableName);
<!--List<User> getUserByTable(@Param("tableName") String tableName);-->
<select id="getUserByTable" resultType="User">
    select * from ${tableName}
</select>

Add Functionality to Retrieve the Auto-Incremented Primary Key

  • Use case
    • t_clazz(clazz_id,clazz_name)
    • t_student(student_id,student_name,clazz_id)
    1. Add class information
    2. Retrieve the ID of the newly added class
    3. Assign students to the class by changing a student's class ID to the ID of the newly added class
  • Set two properties in mapper.xml
    • useGeneratedKeys: Specifies whether to use an auto-incremented primary key
    • keyProperty: Because insert, delete, and update operations all return the same value—the number of affected rows—the retrieved auto-incremented primary key can only be stored in a property of the user object passed as a parameter.
/**
 * 添加用户信息
 * @param user 
 * @date 2022/2/27 15:04
 */
void insertUser(User user);
<!--void insertUser(User user);-->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
    insert into t_user values (null,#{username},#{password},#{age},#{sex},#{email})
</insert>
//测试类
@Test
public void insertUser() {
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
    User user = new User(null, "ton", "123", 23, "男", "[email protected]");
    mapper.insertUser(user);
    System.out.println(user);
    //输出:user{id=10, username='ton', password='123', age=23, sex='男', email='[email protected]'},自增主键存放到了user的id属性中
}

Custom Mapping with resultMap

resultMap handles the mapping between fields and properties

  • resultMap: Configure a custom mapping
    • Attributes:
      • id: The unique identifier for the custom mapping; it must not be duplicated
      • type: The type of the entity class to which the query results are mapped
    • Child tags:
      • id: Configure the mapping for the primary key
      • result: Configure the mapping for a regular field
      • Child tag attributes:
        • property: The name of the property in the entity class used in the mapping
        • column: The name of the field in the table used in the mapping
  • If a field name does not match the corresponding property name in the entity class, you can configure a custom mapping with resultMap. Even properties whose field and property names match must be mapped—in other words, all properties must be listed.
<resultMap id="empResultMap" type="Emp">
    <id property="eid" column="eid"></id>
    <result property="empName" column="emp_name"></result>
    <result property="age" column="age"></result>
    <result property="sex" column="sex"></result>
    <result property="email" column="email"></result>
</resultMap>
<!--List<Emp> getAllEmp();-->
<select id="getAllEmp" resultMap="empResultMap">
    select * from t_emp
</select>
  • If a field name does not match the name of the corresponding property in the entity class, but follows database naming conventions (using underscores) while the entity class property follows Java naming conventions (using camel case), you can also handle the mapping between the field name and the entity class property in either of the following two ways:

    1. Give the field an alias to make it match the entity class property name.
      <!--List<Emp> getAllEmp();-->
      <select id="getAllEmp" resultType="Emp">
          select eid,emp_name empName,age,sex,email from t_emp
      </select>
      
    2. In the setting tag in MyBatis's core configuration file, you can set the global configuration option mapUnderscoreToCamelCase. When querying data from a table, this automatically converts field names that use underscores to camel case. For example, if the field name is user_name and mapUnderscoreToCamelCase is enabled, it will be converted to userName. Detailed Explanation of the Core Configuration File
      
      
    <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> ```

Many-to-One Mapping

Query employee information and the corresponding department information.

public class Emp {  
    private Integer eid;  
    private String empName;  
    private Integer age;  
    private String sex;  
    private String email;  
    private Dept dept;
    //...构造器、get、set方法等
}

Cascading Mapping Relationships

<resultMap id="empAndDeptResultMapOne" type="Emp">
    <id property="eid" column="eid"></id>
    <result property="empName" column="emp_name"></result>
    <result property="age" column="age"></result>
    <result property="sex" column="sex"></result>
    <result property="email" column="email"></result>
    <result property="dept.did" column="did"></result>
    <result property="dept.deptName" column="dept_name"></result>
</resultMap>
<!--Emp getEmpAndDept(@Param("eid")Integer eid);-->
<select id="getEmpAndDept" resultMap="empAndDeptResultMapOne">
    select * from t_emp left join t_dept on t_emp.eid = t_dept.did where t_emp.eid = #{eid}
</select>

Using association to Handle Mapping Relationships

  • association: handles many-to-one mapping relationships
  • property: the name of the property that needs to handle the many-to-one mapping relationship
  • javaType: the type of that property
<resultMap id="empAndDeptResultMapTwo" type="Emp">
    <id property="eid" column="eid"></id>
    <result property="empName" column="emp_name"></result>
    <result property="age" column="age"></result>
    <result property="sex" column="sex"></result>
    <result property="email" column="email"></result>
    <association property="dept" javaType="Dept">
        <id property="did" column="did"></id>
        <result property="deptName" column="dept_name"></result>
    </association>
</resultMap>
<!--Emp getEmpAndDept(@Param("eid")Integer eid);-->
<select id="getEmpAndDept" resultMap="empAndDeptResultMapTwo">
    select * from t_emp left join t_dept on t_emp.eid = t_dept.did where t_emp.eid = #{eid}
</select>

Step-by-step Query

1. Query Employee Information

  • select: Set the unique identifier for the distributed query SQL (namespace.SQLId or the fully qualified name of the mapper interface and method)
  • column: Set the conditions for the step-by-step query
//EmpMapper里的方法
/**
 * 通过分步查询,员工及所对应的部门信息
 * 分步查询第一步:查询员工信息
 * @param  
 * @return com.atguigu.mybatis.pojo.Emp
 * @date 2022/2/27 20:17
 */
Emp getEmpAndDeptByStepOne(@Param("eid") Integer eid);
<resultMap id="empAndDeptByStepResultMap" type="Emp">
    <id property="eid" column="eid"></id>
    <result property="empName" column="emp_name"></result>
    <result property="age" column="age"></result>
    <result property="sex" column="sex"></result>
    <result property="email" column="email"></result>
    <association property="dept"
                 select="com.atguigu.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
                 column="did"></association>
</resultMap>
<!--Emp getEmpAndDeptByStepOne(@Param("eid") Integer eid);-->
<select id="getEmpAndDeptByStepOne" resultMap="empAndDeptByStepResultMap">
    select * from t_emp where eid = #{eid}
</select>

2. Query Department Information

//DeptMapper里的方法
/**
 * 通过分步查询,员工及所对应的部门信息
 * 分步查询第二步:通过did查询员工对应的部门信息
 * @param
 * @return com.atguigu.mybatis.pojo.Emp
 * @date 2022/2/27 20:23
 */
Dept getEmpAndDeptByStepTwo(@Param("did") Integer did);
<!--此处的resultMap仅是处理字段和属性的映射关系-->
<resultMap id="EmpAndDeptByStepTwoResultMap" type="Dept">
    <id property="did" column="did"></id>
    <result property="deptName" column="dept_name"></result>
</resultMap>
<!--Dept getEmpAndDeptByStepTwo(@Param("did") Integer did);-->
<select id="getEmpAndDeptByStepTwo" resultMap="EmpAndDeptByStepTwoResultMap">
    select * from t_dept where did = #{did}
</select>

One-to-Many Mapping Handling

public class Dept {
    private Integer did;
    private String deptName;
    private List<Emp> emps;
    //...构造器、get、set方法等
}

collection

  • collection: Used to handle one-to-many mapping relationships
  • ofType: Indicates the type of data stored in the collection corresponding to this property
<resultMap id="DeptAndEmpResultMap" type="Dept">
    <id property="did" column="did"></id>
    <result property="deptName" column="dept_name"></result>
    <collection property="emps" ofType="Emp">
        <id property="eid" column="eid"></id>
        <result property="empName" column="emp_name"></result>
        <result property="age" column="age"></result>
        <result property="sex" column="sex"></result>
        <result property="email" column="email"></result>
    </collection>
</resultMap>
<!--Dept getDeptAndEmp(@Param("did") Integer did);-->
<select id="getDeptAndEmp" resultMap="DeptAndEmpResultMap">
    select * from t_dept left join t_emp on t_dept.did = t_emp.did where t_dept.did = #{did}
</select>

Step-by-Step Query

1. Query Department Information

/**
 * 通过分步查询,查询部门及对应的所有员工信息
 * 分步查询第一步:查询部门信息
 * @param did 
 * @return com.atguigu.mybatis.pojo.Dept
 * @date 2022/2/27 22:04
 */
Dept getDeptAndEmpByStepOne(@Param("did") Integer did);
<resultMap id="DeptAndEmpByStepOneResultMap" type="Dept">
    <id property="did" column="did"></id>
    <result property="deptName" column="dept_name"></result>
    <collection property="emps"
                select="com.atguigu.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
                column="did"></collection>
</resultMap>
<!--Dept getDeptAndEmpByStepOne(@Param("did") Integer did);-->
<select id="getDeptAndEmpByStepOne" resultMap="DeptAndEmpByStepOneResultMap">
    select * from t_dept where did = #{did}
</select>

2. Query all employees in a department by department ID

/**
 * 通过分步查询,查询部门及对应的所有员工信息
 * 分步查询第二步:根据部门id查询部门中的所有员工
 * @param did
 * @return java.util.List<com.atguigu.mybatis.pojo.Emp>
 * @date 2022/2/27 22:10
 */
List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);
<!--List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);-->
<select id="getDeptAndEmpByStepTwo" resultType="Emp">
    select * from t_emp where did = #{did}
</select>

Lazy Loading

  • Advantages of step-by-step queries: they enable lazy loading, but global configuration must be set in the core configuration file:
    • lazyLoadingEnabled: Global switch for lazy loading. When enabled, all associated objects are loaded lazily
    • aggressiveLazyLoading: When enabled, calling any method loads all properties of the object. Otherwise, each property is loaded as needed
  • This enables loading data on demand: only the corresponding SQL is executed for the data being retrieved. You can use the fetchType attribute in association and collection to specify whether the current step-by-step query uses lazy loading: fetchType="lazy (lazy loading)|eager (immediate loading)"
<settings>
    <!--开启延迟加载-->
    <setting name="lazyLoadingEnabled" value="true"/>
</settings>
@Test
public void getEmpAndDeptByStepOne() {
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    Emp emp = mapper.getEmpAndDeptByStepOne(1);
    System.out.println(emp.getEmpName());
}
  • With lazy loading disabled, both SQL statements ran.
  • With lazy loading enabled, only the SQL statement for fetching emp ran.
@Test
public void getEmpAndDeptByStepOne() {
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    Emp emp = mapper.getEmpAndDeptByStepOne(1);
    System.out.println(emp.getEmpName());
    System.out.println("----------------");
    System.out.println(emp.getDept());
}
  • After this is enabled, the corresponding SQL statement is called only when a query needs to access dept.

  • fetchType: When global lazy loading is enabled, this property can be used to manually control lazy loading behavior. fetchType="lazy (lazy loading)|eager (immediate loading)"

    <resultMap id="empAndDeptByStepResultMap" type="Emp">
        <id property="eid" column="eid"></id>
        <result property="empName" column="emp_name"></result>
        <result property="age" column="age"></result>
        <result property="sex" column="sex"></result>
        <result property="email" column="email"></result>
        <association property="dept"
                     select="com.atguigu.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
                     column="did"
                     fetchType="lazy"></association>
    </resultMap>
    

Dynamic SQL

  • MyBatis's dynamic SQL feature dynamically assembles SQL statements based on specific conditions. It exists to address the pain points of concatenating SQL statement strings.

if

  • The if tag evaluates the expression in its test attribute (that is, the data passed in). If the expression evaluates to true, the content inside the tag is executed; otherwise, it is not.
  • Add an always-true condition after where: 1=1
    • This always-true condition does not affect the query results.
    • This 1=1 can be used to concatenate and statements. For example, when empName is null:
      • If the always-true condition is not added, the SQL statement is select * from t_emp where and age = ? and sex = ? and email = ?. In this case, where is used together with and, causing an SQL error.
      • If an always-true condition is added, the SQL statement is select * from t_emp where 1= 1 and age = ? and sex = ? and email = ?, and no error occurs.
<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
    select * from t_emp where 1=1
    <if test="empName != null and empName !=''">
        and emp_name = #{empName}
    </if>
    <if test="age != null and age !=''">
        and age = #{age}
    </if>
    <if test="sex != null and sex !=''">
        and sex = #{sex}
    </if>
    <if test="email != null and email !=''">
        and email = #{email}
    </if>
</select>

where

  • where is generally used together with if:
    • If none of the if conditions in the where tag are met, the where tag has no effect, meaning it will not add the where keyword.
    • If an if condition in the where tag is met, the where tag automatically adds the where keyword and removes any redundant and or or at the beginning of the conditions.
<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
    select * from t_emp
    <where>
        <if test="empName != null and empName !=''">
            emp_name = #{empName}
        </if>
        <if test="age != null and age !=''">
            and age = #{age}
        </if>
        <if test="sex != null and sex !=''">
            and sex = #{sex}
        </if>
        <if test="email != null and email !=''">
            and email = #{email}
        </if>
    </where>
</select>
  • Note: The where tag cannot remove extra and/or operators after conditions.

    <!--这种用法是错误的,只能去掉条件前面的and/or,条件后面的不行-->
    <if test="empName != null and empName !=''">
    emp_name = #{empName} and
    </if>
    <if test="age != null and age !=''">
        age = #{age}
    </if>
    

trim

  • trim is used to remove or add content within a tag
  • Common attributes
    • prefix: adds content before the content inside the trim tag
    • suffix: adds content after the content inside the trim tag
    • prefixOverrides: removes content from the beginning of the content inside the trim tag
    • suffixOverrides: removes content from the end of the content inside the trim tag
  • If none of the tags inside trim meet the conditions, the trim tag has no effect, leaving only select * from t_emp
<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
    select * from t_emp
    <trim prefix="where" suffixOverrides="and|or">
        <if test="empName != null and empName !=''">
            emp_name = #{empName} and
        </if>
        <if test="age != null and age !=''">
            age = #{age} and
        </if>
        <if test="sex != null and sex !=''">
            sex = #{sex} or
        </if>
        <if test="email != null and email !=''">
            email = #{email}
        </if>
    </trim>
</select>
//测试类
@Test
public void getEmpByCondition() {
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
    List<Emp> emps= mapper.getEmpByCondition(new Emp(null, "张三", null, null, null, null));
    System.out.println(emps);
}

choose、when、otherwise

  • choose、when、otherwise is equivalent to if...else if..else
  • There must be at least one when, and at most one otherwise.
<select id="getEmpByChoose" resultType="Emp">
    select * from t_emp
    <where>
        <choose>
            <when test="empName != null and empName != ''">
                emp_name = #{empName}
            </when>
            <when test="age != null and age != ''">
                age = #{age}
            </when>
            <when test="sex != null and sex != ''">
                sex = #{sex}
            </when>
            <when test="email != null and email != ''">
                email = #{email}
            </when>
            <otherwise>
                did = 1
            </otherwise>
        </choose>
    </where>
</select>
@Test
public void getEmpByChoose() {
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
    List<Emp> emps = mapper.getEmpByChoose(new Emp(null, "张三", 23, "男", "[email protected]", null));
    System.out.println(emps);
}
  • Equivalent to if a else if b else if c else d; only one of them will be executed

foreach

  • Attributes:

    • collection: Specifies the array or collection to iterate over
    • item: Represents each item in the collection or array
    • separator: Specifies the separator between loop bodies. A space is added before and after the separator by default, such as ,
    • open: Specifies the opening token for the content in the foreach tag
    • close: Specifies the closing token for the content in the foreach tag
  • Batch delete

    <!--int deleteMoreByArray(Integer[] eids);-->
    <delete id="deleteMoreByArray">
        delete from t_emp where eid in
        <foreach collection="eids" item="eid" separator="," open="(" close=")">
            #{eid}
        </foreach>
    </delete>
    
    @Test
    public void deleteMoreByArray() {
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
        int result = mapper.deleteMoreByArray(new Integer[]{6, 7, 8, 9});
        System.out.println(result);
    }
    

  • Batch Add

    <!--int insertMoreByList(@Param("emps") List<Emp> emps);-->
    <insert id="insertMoreByList">
        insert into t_emp values
        <foreach collection="emps" item="emp" separator=",">
            (null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.email},null)
        </foreach>
    </insert>
    
    @Test
    public void insertMoreByList() {
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
        Emp emp1 = new Emp(null,"a",1,"男","[email protected]",null);
        Emp emp2 = new Emp(null,"b",1,"男","[email protected]",null);
        Emp emp3 = new Emp(null,"c",1,"男","[email protected]",null);
        List<Emp> emps = Arrays.asList(emp1, emp2, emp3);
        int result = mapper.insertMoreByList(emps);
        System.out.println(result);
    }
    

SQL Fragments

  • SQL fragments can be used to define reusable SQL code, which can then be included wherever needed using the include tag.
  • Declare an SQL fragment: <sql> tag
<sql id="empColumns">eid,emp_name,age,sex,email</sql>

Quoted SQL snippet: <include> tag

<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
    select <include refid="empColumns"></include> from t_emp
</select>

MyBatis Caching

MyBatis First-Level Cache

  • The first-level cache is scoped to the SqlSession. Data queried through the same SqlSession is cached; the next time the same data is queried, it is retrieved directly from the cache without accessing the database again.

  • Four cases that invalidate the first-level cache:

    1. Different SqlSession instances have different first-level caches.
    2. The same SqlSession is used, but the query conditions differ.
    3. Any insert, delete, or update operation is performed between two queries in the same SqlSession.
    4. The cache is manually cleared between two queries in the same SqlSession.

MyBatis Second-Level Cache

  • The second-level cache is scoped to the SqlSessionFactory. Results of queries performed by SqlSession instances created by the same SqlSessionFactory are cached; if the same query is executed again later, its results are retrieved from the cache.

  • Conditions for enabling the second-level cache

    1. Set the global configuration property cacheEnabled="true" in the core configuration file. It defaults to true, so you do not need to set it.
    2. Set the <cache /> tag in the mapper file.
    3. The second-level cache is only effective after the SqlSession is closed or committed.
    4. The entity class type to which the queried data is converted must implement the Serializable interface.
  • Cases that invalidate the second-level cache: Performing any insert, delete, or update operation between two queries invalidates both the first-level and second-level caches.

Second-Level Cache Configuration

  • The cache tag added to the mapper configuration file can be used to set several properties.
  • eviction property: Cache eviction strategy
    • LRU (Least Recently Used) – Removes objects that have not been used for the longest time.
    • FIFO (First In, First Out) – Removes objects in the order they entered the cache.
    • SOFT – Soft references: Removes objects based on the state of the garbage collector and the rules for soft references.
    • WEAK – Weak references: Removes objects more aggressively based on the state of the garbage collector and the rules for weak references.
    • The default is LRU.
  • flushInterval property: Refresh interval, in milliseconds.
    • By default, no refresh interval is set; the cache is refreshed only when a mapped statement is called (insert, delete, or update).
  • size property: Number of references; a positive integer.
    • Indicates the maximum number of objects the cache can store. Setting it too high can easily cause an out-of-memory error.
  • readOnly property: Read-only, true/false
    • true: Read-only cache; the same instance of the cached object is returned to all callers. Therefore, these objects cannot be modified. This provides an important performance advantage.
    • false: Read-write cache; a copy of the cached object is returned (via serialization). This is slower but safer, so the default is false.

Order of MyBatis Cache Queries

  • The second-level cache is queried first, because it may contain data that other programs have already queried and that can be used directly.
  • If the second-level cache misses, the first-level cache is queried.
  • If the first-level cache also misses, the database is queried.
  • After the SqlSession is closed, data in the first-level cache is written to the second-level cache.

Integrating the Third-Party EHCache Cache (For Reference)

Add Dependencies

<!-- Mybatis EHCache整合包 -->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.1</version>
</dependency>
<!-- slf4j日志门面的一个具体实现 -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>

Functions of Each JAR Package

JAR package name Purpose
mybatis-ehcache Integration package for MyBatis and EHCache
ehcache EHCache core package
slf4j-api SLF4J logging facade package
logback-classic A concrete implementation that supports the SLF4J facade interface

Create the EHCache configuration file ehcache.xml

  • The name must be ehcache.xml
<?xml version="1.0" encoding="utf-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <!-- 磁盘保存路径 -->
    <diskStore path="D:\atguigu\ehcache"/>
    <defaultCache
            maxElementsInMemory="1000"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>

Set the Type of the Second-Level Cache

  • Set the second-level cache type in the xxxMapper.xml file.
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

Add logback logging

  • When SLF4J is present, log4j, which serves as a simple logging framework, will become inactive. In this case, we need to use logback, an implementation of SLF4J, to print logs. Create the logback configuration file logback.xml; its name is fixed and must not be changed.
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <!-- 指定日志输出的位置 -->
    <appender name="STDOUT"
              class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!-- 日志输出的格式 -->
            <!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体内容、换行 -->
            <pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern>
        </encoder>
    </appender>
    <!-- 设置全局日志级别。日志级别按顺序分别是:DEBUG、INFO、WARN、ERROR -->
    <!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
    <root level="DEBUG">
        <!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
        <appender-ref ref="STDOUT" />
    </root>
    <!-- 根据特殊需求指定局部日志级别 -->
    <logger name="com.atguigu.crowd.mapper" level="DEBUG"/>
</configuration>

EHCache Configuration File Description

Property Name Required Description
maxElementsInMemory Yes Maximum number of elements cached in memory
maxElementsOnDisk Yes Maximum number of elements cached on disk; 0 means unlimited
eternal Yes Specifies whether cached elements never expire. If true, cached data is always valid; if false, timeToIdleSeconds and timeToLiveSeconds are also used to determine expiration
overflowToDisk Yes Specifies whether expired elements are cached to disk when the in-memory cache overflows
timeToIdleSeconds No When the time between two consecutive accesses to data cached in EhCache exceeds the value of the timeToIdleSeconds property, that data is deleted. The default value is 0, meaning the idle time is unlimited
timeToLiveSeconds No Valid lifetime of a cached element. The default value is 0, meaning the element's lifetime is unlimited
diskSpoolBufferSizeMB No Buffer size for DiskStore (disk cache). The default is 30 MB. Each cache should have its own buffer
diskPersistent No Whether to persist data in EhCache to disk when the VM restarts. The default is false
diskExpiryThreadIntervalSeconds No Interval at which the disk cache cleanup thread runs. The default is 120 seconds. Every 120 seconds, the thread performs a cleanup of data in EhCache
memoryStoreEvictionPolicy No Policy for removing elements from the cache when the in-memory cache reaches its maximum and a new element is added. The default is LRU (Least Recently Used); options also include LFU (Least Frequently Used) and FIFO (First In, First Out)

MyBatis Reverse Engineering

  • Forward engineering: Create Java entity classes first, and let the framework generate database tables based on them. Hibernate supports forward engineering
  • Reverse engineering: Create database tables first, and let the framework generate the following resources based on the tables:
    • Java entity classes
    • Mapper interfaces
    • Mapper mapping files

Steps for Creating a Reverse Engineering Project

Add Dependencies and Plugins

<dependencies>
    <!-- MyBatis核心依赖包 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.9</version>
    </dependency>
    <!-- junit测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>
    <!-- MySQL驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.27</version>
    </dependency>
    <!-- log4j日志 -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
</dependencies>
<!-- 控制Maven在构建过程中相关配置 -->
<build>
    <!-- 构建过程中用到的插件 -->
    <plugins>
        <!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.0</version>
            <!-- 插件的依赖 -->
            <dependencies>
                <!-- 逆向工程的核心依赖 -->
                <dependency>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-core</artifactId>
                    <version>1.3.2</version>
                </dependency>
                <!-- 数据库连接池 -->
                <dependency>
                    <groupId>com.mchange</groupId>
                    <artifactId>c3p0</artifactId>
                    <version>0.9.2</version>
                </dependency>
                <!-- MySQL驱动 -->
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.27</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

Create the MyBatis Core Configuration File

<?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>
    <properties resource="jdbc.properties"/>
    <typeAliases>
        <package name=""/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name=""/>
    </mappers>
</configuration>

Creating a Reverse Engineering Configuration File

  • The filename must be: generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--
    targetRuntime: 执行生成的逆向工程的版本
    MyBatis3Simple: 生成基本的CRUD(清新简洁版)
    MyBatis3: 生成带条件的CRUD(奢华尊享版)
    -->
    <context id="DB2Tables" targetRuntime="MyBatis3Simple">
        <!-- 数据库的连接信息 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis"
                        userId="root"
                        password="123456">
        </jdbcConnection>
        <!-- javaBean的生成策略-->
        <javaModelGenerator targetPackage="com.atguigu.mybatis.pojo" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- SQL映射文件的生成策略 -->
        <sqlMapGenerator targetPackage="com.atguigu.mybatis.mapper"
                         targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- Mapper接口的生成策略 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.atguigu.mybatis.mapper" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 逆向分析的表 -->
        <!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
        <!-- domainObjectName属性指定生成出来的实体类的类名 -->
        <table tableName="t_emp" domainObjectName="Emp"/>
        <table tableName="t_dept" domainObjectName="Dept"/>
    </context>
</generatorConfiguration>

Execute the MBG plugin's generate goal

  • If the following error occurs: Exception getting JDBC Driver, the database driver configuration in pom.xml may be incorrect
  • The driver in the dependency
  • The driver in the mybatis-generator-maven-plugin plugin
  • The driver versions in both should be the same
  • Execution result

QBC

Query

  • selectByExample: Query by conditions; an example object or null must be passed in. If null is passed, it means there are no conditions—in other words, all data is queried
  • example.createCriteria().xxx: Create a condition object, and add query conditions to the SQL using the andXXX methods. Each condition is joined with AND
  • example.or().xxx: Join other conditions to the previously added conditions using OR
@Test public void testMBG() throws IOException {
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    EmpExample example = new EmpExample();
    //名字为张三,且年龄大于等于20
    example.createCriteria().andEmpNameEqualTo("张三").andAgeGreaterThanOrEqualTo(20);
    //或者did不为空
    example.or().andDidIsNotNull();
    List<Emp> emps = mapper.selectByExample(example);
    emps.forEach(System.out::println);
}

Additions and Modifications

  • updateByPrimaryKey: Modify data by primary key. If a value is null, the corresponding field will also be set to null.
  • mapper.updateByPrimaryKey(new Emp(1,"admin",22,null,"[email protected]",3));
  • updateByPrimaryKeySelective(): Selectively modify data by primary key. If a value is null, the corresponding field will not be modified.
  • mapper.updateByPrimaryKeySelective(new Emp(2,"admin2",22,null,"[email protected]",3));

Pagination Plugin

Steps for Using the Pagination Plugin

Add the Dependency

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.2.0</version>
</dependency>

Configure the Pagination Plugin

  • Configure the plugin in the MyBatis core configuration file (mybatis-config.xml)
<plugins>
    <!--设置分页插件-->
    <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>

Using the Pagination Plugin

Enabling Pagination

  • Use PageHelper.startPage(int pageNum, int pageSize) before the query function to enable pagination
    • pageNum: the current page number
    • pageSize: the number of items displayed per page
@Test
public void testPageHelper() throws IOException {
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    //访问第一页,每页四条数据
    PageHelper.startPage(1,4);
    List<Emp> emps = mapper.selectByExample(null);
    emps.forEach(System.out::println);
}

Pagination-Related Data

Method One: Direct Output

@Test
public void testPageHelper() throws IOException {
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    //访问第一页,每页四条数据
    Page<Object> page = PageHelper.startPage(1, 4);
    List<Emp> emps = mapper.selectByExample(null);
    //在查询到List集合后,打印分页数据
    System.out.println(page);
}
  • Pagination-related data:

    Page{count=true, pageNum=1, pageSize=4, startRow=0, endRow=4, total=8, pages=2, reasonable=false, pageSizeZero=false}[Emp{eid=1, empName='admin', age=22, sex='男', email='[email protected]', did=3}, Emp{eid=2, empName='admin2', age=22, sex='男', email='[email protected]', did=3}, Emp{eid=3, empName='王五', age=12, sex='女', email='[email protected]', did=3}, Emp{eid=4, empName='赵六', age=32, sex='男', email='[email protected]', did=1}]
    

Method Two: Use PageInfo

  • After querying to obtain the list collection, use PageInfo<T> pageInfo = new PageInfo<>(List<T> list, intnavigatePages) to get pagination-related data
    • list: Data after pagination
    • navigatePages: Number of page numbers in the navigation bar
@Test
public void testPageHelper() throws IOException {
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    PageHelper.startPage(1, 4);
    List<Emp> emps = mapper.selectByExample(null);
    PageInfo<Emp> page = new PageInfo<>(emps,5);
    System.out.println(page);
}
  • Pagination-related data:

    PageInfo{
    pageNum=1, pageSize=4, size=4, startRow=1, endRow=4, total=8, pages=2, 
    list=Page{count=true, pageNum=1, pageSize=4, startRow=0, endRow=4, total=8, pages=2, reasonable=false, pageSizeZero=false}[Emp{eid=1, empName='admin', age=22, sex='男', email='[email protected]', did=3}, Emp{eid=2, empName='admin2', age=22, sex='男', email='[email protected]', did=3}, Emp{eid=3, empName='王五', age=12, sex='女', email='[email protected]', did=3}, Emp{eid=4, empName='赵六', age=32, sex='男', email='[email protected]', did=1}], 
    prePage=0, nextPage=2, isFirstPage=true, isLastPage=false, hasPreviousPage=false, hasNextPage=true, navigatePages=5, navigateFirstPage=1, navigateLastPage=2, navigatepageNums=[1, 2]}
    
  • The data in list is the same as the page data returned directly by Method 1.

Common fields:

  • pageNum: Current page number
  • pageSize: Number of items displayed per page
  • size: Actual number of items on the current page
  • total: Total number of records
  • pages: Total number of pages
  • prePage: Previous page number
  • nextPage: Next page number
  • isFirstPage/isLastPage: Whether this is the first/last page
  • hasPreviousPage/hasNextPage: Whether a previous/next page exists
  • navigatePages: Number of page numbers in the pagination navigation
  • navigatepageNums: Page numbers in the pagination navigation, [1,2,3,4,5]