[精选]⭐MyBatis(全面+细节+新手)⭐【这一篇就ok!】

目录

1.Mybatis简介🤶🤶🤶

2.搭建Mybatis 🤶🤶🤶

 3.核心配置文件🤶🤶🤶

4.Mybaits获取参数值的两种方式🤶🤶🤶

5.Mybatis的各种查询功能🤶🤶🤶

6.特殊SQL的执行🤶🤶🤶

7.自定义映射🤶🤶🤶

8.动态SQL  🤶🤶🤶

9.Mybatis缓存🤶🤶🤶

10.Mybatis逆向工程🤶🤶🤶

11.分页插件🤶🤶🤶


1.Mybatis简介🤶🤶🤶

1.1mybatis历史

MyBatis最初是Apache的一个开源项目iBatis, 2010年6月这个项目由Apache Software Foundation迁移到了Google Code。

随着开发团队转投Google Code旗下, iBatis3.x正式更名为MyBatis,代码于2013年11月迁移到GithubiBatis一词来源于"internet"和"abatis"的组合,是一个基于Java的持久层框架。

iBatis提供的持久层框架包括sQLMapsData Access Objects (DAO)

1.2mybatis特性

  1. MyBatis 是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架
  2. MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。
  3. MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO (Plain OldJava Objects,普通的Java对象)映射成数据库中的记录。
  4. MyBatis 是一个半自动的ORM (Object Relation Mapping)框架。
  5. Mybatis就是帮助程序员将数据存取到数据库里面。

2.搭建Mybatis 🤶🤶🤶

2.1开发环境

IDEA:2021.2

JDK:1.8

Maven:3.8.1

Mysq版本:mysql 8.33

Mybatis:mybatis 5.3.7

 2.2创建模块

使用自己的maven!!!

2.2.1导入依赖

      <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>8.0.33</version>
        </dependency>
     </dependencies>

2.2.3Mybatis核心配置文件

<?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"/>


    <!--设置类型别名-->
    <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>

2.3.4创建实体类

public class User {
    private Integer id;
    private String userName;
    private String password;
    private Integer age;
    private String sex;
    private String email;

    public User() {
    }

    public User(Integer id, String userName, String password, Integer age, String sex, String email) {
        this.id = id;
        this.userName = userName;
        this.password = password;
        this.age = age;
        this.sex = sex;
        this.email = email;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

2.3.5创建mapper接口

public interface UserMapper {

    /**
     * 添加用户信息
     */
    int  insertUser();

    /**
     * 修改用户信息
     */

    int updateUser();

    /**
     * 删除用户
     */
    int deleteUser();

    /**
     * 根据id查用户
     */
    User getById();

    /**
     * 查询所有用户
     */
    List<User> getAllUser();

}

2.3.5创建映射文件

相关概念: ORM (Object Relationship Mapping)对象关系映射。

  • 对象:Java的实体类对象
  • 关系:关系型数据
  • 库映射:二者之间的对应关系
java数据库
属性字段/列
对象

记录/行

 1、映射文件的命名规则:表所对应的实体类类名+Mapper.xml

例如:表t_user,映射的实体类为User,所对应的映射文件为UserMapper.xml

 Mybatis面向接口编程的两个一致:

  • 1.映射文件的namespace要和mapper接口的全类名保持一致
  • 2.映射文件中sql语句的id要和mapper接口中的方法名一致 
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.xz.mapper.UserMapper">

    <!--int  insertUser();-->
    <insert id="insertUser">
        insert into t_user values(null,'冷落风','6',90,'男','123456@qq.com')
    </insert>


    <!-- int updateUser();-->
    <update id="updateUser">
        update t_user set username='张三' where id=18
    </update>

    <!--int deleteUser();-->
    <delete id="deleteUser">
        delete from t_user where id=19
    </delete>


    <!--
     查询功能的标签必须设置resultType或resultMap
     resultType:设置默认映射关系
     resultMap:设置自定义映射关系
    -->
    <!--User getById();-->
    <select id="getById" resultType="com.xz.pojo.User">
        select * from t_user where id=3
    </select>



    <!-- List<User> getAllUser();-->
    <select id="getAllUser" resultType="com.xz.pojo.User">
        select * from t_user
    </select>
</mapper>

2.3.5测试

public class TestMybatis {
    @Test
    public void test1() throws Exception {
        //1.加载核心配置文件
        InputStream resource = Resources.getResourceAsStream("mybatis-config.xml");

        //2.获取SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

        //3.获取sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resource);

        //4.获取mybatis操作数据库的会话对象SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //5.获取mapper接口对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //6.调用方法测试
        int row = mapper.insertUser();
        System.out.println("执行"+row+"行");
    }
}

注意:

SqlSession默认不自动提交事务

若需要自动提交事务sqlSessionFactory.openSession(true)

 3.核心配置文件🤶🤶🤶

<?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"/>

    <!--设置类型别名:类名且不区分大小写-->
    <!--
      typeAliases:设置某个类型别名
      属性:
        type:设置别名的类型
        alias:设置类型别名
    -->
    <typeAliases>
        <!--以包为单位,将包下所有的类型设置默认的类型别名,既类名且不区分大小写  -->
        <package name="com.xz.pojo"/>
    </typeAliases>
    <!--    <typeAliases>-->
    <!--        <typeAlias type="com.xz.pojo.User" alias=""></typeAlias>-->
    <!--    </typeAliases>-->


    <!--设置连接数据库的环境-->
    <!--
       environments:配置多个连接数据库的环境
       属性:
        default:设置默认使用的环境的id
    -->
    <environments default="development">
        <!--
        environment:配置某个具体环境
        属性:
           id:表示连接数据库环境的唯一标识,不能重复
        -->
        <environment id="development">
            <!--
               transactionManager:设置事务管理方式
               属性:
                   type:"JDBC/MANAGED"
                   JDBC:表示当前环境中,执行sql时,使用的是原生的事务管理方式
                   MANAGED:表示被管理
            -->
            <transactionManager type="JDBC"/>
            <!--
              dataSource:配置数据源
              属性:
                 type:设置数据源类型
                  type=“POOLED|UNPOOLED|JNDI”
                  POOLED:表示使用数据库连接池缓存数据库连接
                  UNPOOLED:表示不使用数据库连接池
                  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>
        <package name="com.xz.mapper"/>
    </mappers>
</configuration>

以包为单位引入映射文件要求:

  • 1.mapper接口所在的包要和映射文件所在的包一致
  • 2.mapper接口要和映射文件的名字一致

在resource下创建目录,中间不能用 . 连接;应用 / 连接!!! 

 

4.Mybaits获取参数值的两种方式🤶🤶🤶

MyBatis获取参数值的两种方式:${}和#{}

  • ${}的本质就是字符串拼接(自身不带单引号)
  • #{}的本质就是占位符赋值(自身带单引号)

 4.1Mybatis获取参数值的各种情况

4.1.1mapper接口的参数为单个字面量类型

可以通过${}或#{}以任意的名称获取参数值,但需要注意${} 的单引号问题

  <!--User getUserByUserName(String username);-->
    <select id="getUserByUserName" resultType="user">
        <!--select * from t_user where username=#{username}-->
        select * from t_user where username='${username}'
    </select>

4.1.2mapper接口的参数为多个

 此时Mybatis会将这些参数放在一个map集合中,以两种方式进行存储

  • 1.以arg0,arg1..为键,以参数为值
  • 2.以param1,param2为键,以参数为值

因此只需要通过#{}或${}以键的方式访问即可,但需要注意${}单引号问题

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

4.1.3mapper接口的参数有多个,手动放入map存储

只需要通过#{}或${}以键的方式访问即可,但需要注意${}单引号问题

 <!--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("mybatis-config.xml");
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String,Object> map=new HashMap<>();
        map.put("username","小张");
        map.put("password","123456");
        User user = mapper.checkLoginByMap(map);
        System.out.println(user);
    }

4.1.4mapper接口是一个实体类类型的参数

只需要通过#{}或${}以属性的方式访问属性值即可,但需要注意${}单引号问题

   <!-- 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("mybatis-config.xml");
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int row = mapper.insertUser(new User(null, "大黑", "999", 89, "男", "123@qq.com"));
        System.out.println("成功添加"+row+"行数据");
    }

4.1.5使用@Parma命名参数

 此时Mybatis会将这些参数放在一个map集合中,以两种方式进行存储

  • 1.以@Parma注解的值为键,以参数为值
  • 2.以param1,param2为键,以参数为值
  • 因此只需要通过#{}或${}以键的方式访问即可,但需要注意${}单引号问题
    /**
     * 登录(使用@Parma)
     */
    User checkLoginByParma(@Param("username")String username,@Param("password")String password);
    <select id="checkLoginByParma" resultType="user">
        select * from t_user where username=#{username} and password=#{password}
    </select>

总结:

分两种情况:

  • 1.实体类类型
  • 2.以@Parma注解命名

5.Mybatis的各种查询功能🤶🤶🤶

Mybatis设置的默认类型别名

java.lang.Integer------->int,integer

int------>_int._integer

Map----->map

String----->String

5.1.查询一个实体类对象

若查询出来的数据只有一条: 

  • 1.可以通过实体类对象
  • 2.可以通过list集合接收
  • 3.可以通过Map集合接收

若查询出来的数据有多条:

  • 1.可以通过实体类类型的list集合接收
  • 2.可以通过map类型的list集合接收
  • 3.可以在mapper接口上的方法上添加@MapKey注解

一定不能通过实体类对象接收,否则报错TooManyResultsException

    /**
     * 根据Id查询用户
     */
    User getUserById(@Param("id") Integer id);
    <select id="getUserById" resultType="user">
        select * from t_user where id=#{id}
    </select>

5.2.查询一个list集合

    /**
     * 查询所有用户信息
     */

    List<User> getAllUser();

    <select id="getAllUser" resultType="user">
        select * from t_user
    </select>

5.3.查询单个数据

    /**
     * 查询用户信息的总数
     */
    Integer getCount();
    <select id="getCount" resultType="Integer">
        select count(*) from t_user
    </select>

5.4.查询一条数据为map集合


    /**
     * 根据id查询用户信息作为一个map集合
     */
    Map<String, Object> getUserToMap(@Param("id") Integer id);
   <select id="getUserToMap" resultType="map">
        select * from t_user where id=#{id}
    </select>

5.5.查询多条数据为map集合

方式一:

    /**
     * 查询所有用户
     */
    List<Map<String, Object>> getAllUserToMap();

方式二:

    /**
     * 查询所有用户
     */
    @MapKey("id")
    Map<String,Object> getAllUserToMap();
    <select id="getAllUserToMap" resultType="map">
        select * from t_user
    </select>

6.特殊SQL的执行🤶🤶🤶

6.1.模糊查询

 三种方式:

  1. select * from t_user where username like '%$fusername}%'
  2. select * from t_user where username like concat('%',#fusername},'%')
  3. select * from t_user where username like "%"#fusername}"%"
 /**
     * 根据用户名模糊查询用户信息
     */
    List<User> getUserByLike(@Param("username")String username);
    <select id="getUserByLike" resultType="user">
        <!--select * from t_user where username like '%${username}%'-->
        <!--select * from t_user where username like concat('%',#{username},'%')-->
        select * from t_user where username like "%"#{username}"%"
    </select>

6.2.批量删除

delete from t_user where id in(${fids})

    /**
     * 批量删除
     */
    int deleteMore(@Param("ids") String ids);
    <delete id="deleteMore">
        delete from t_user where id in(${ids})
    </delete>

6.3.动态设置表明

     /**
      * 查询指定表中的数据
      */

    List<User> getUserByTableName(@Param("tableName") String tableName);
   <select id="getUserByTableName" resultType="user">
        select * from ${tableName}
    </select>

6.4.添加功能自动获取主键

    /**
     * 添加用户信息
     */
    int insertUser(User user);

 属性的含义:

  1.  userGenerateKeys:设置当前标签中的sql使用了自增的id
  2.  KeyProperty:将自增的主键的值赋值给传输到映射文件中参数的某个属性
    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
        insert into t_user values(null,#{userName},#{password},#{age},#{sex},#{email})
    </insert>

 

7.自定义映射🤶🤶🤶

7.1字段名和属性名不一致

  • mysql的命名规则 下划线 eg:emp_name
  • java的命名规则驼峰         eg:empName;

两者需要对应,则需要一定的关系

7.1.1为字段起别名

    <select id="getAllEmp" resultType="emp">
        select emp_id empId,emp_name empName, age,sex,email from t_emp
    </select>

7.1.2全局配置⭐⭐

 在mybatis核心配置文件中配置,将下划线自动映射驼峰 eg:emp_name---->empName

   <!--设置Mybatis的全局配置-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

7.1.3resultMap自定义映射关系

resultMap:设置自定义映射关系

属性:

  • id:唯一标识,不能重复
  • type:设置映射关系中的实体类类型

子标签:

  • id:设置主键的元素关系
  • result:设置普通字段映射关系

子标签属性

  •  property:设置映射关系中的属性名,必须是type属性所设置的实体类类型中的属性名
  • colum:设置映射关系中的字段名,必须是sql语句查询出的字段名

注意:增,删,改,不用resultMap/resultType,仅在select中用到!!!!

    <resultMap id="empResultMap" type="emp">
        <id property="empId" column="emp_id"></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>

7.2多对一映射


    /**
     * 查询员工以及员工所对应的部门
     */
    Emp getEmpAndDept(@Param("empId") Integer empId);

7.2.1级联属性赋值

对象.属性的方式 eg:dept.deptName

    <resultMap id="empAndDeptResultMapOne" type="emp">
        <id property="empId" column="emp_id"></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.deptId" column="dept_id"></result>
        <result property="dept.deptName" column="dept_name"></result>
    </resultMap>
    
    <!-- Emp getEmpAndDept(@Param("empId") Integer empId);-->
    <select id="getEmpAndDept" resultMap="empAndDeptResultMapOne" >
        select * from t_emp left join t_dept on t_emp.did=t_dept.dept_id where t_emp.emp_id=#{empId}
    </select>

7.2.2association

  • association:处理多对一映射关系
  • property:需要处理多对一映射关系的属性名
  • javaType:改属性的类型
    <resultMap id="empAndDeptResultMapTwo" type="emp">
        <id property="empId" column="emp_id"></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="deptId" column="dept_id"></id>
          <result property="deptName" column="dept_name"></result>
      </association>
    </resultMap>

7.2.3association分步

  • property:多对应的属性
  • select:分布查询的sql的唯一标识(namespace.SQLId或mapper接口的全类名.方法名)
  • colum:设置分布查询的条件 
  • fetchType:当开启全局的延迟加载之后,可通过此属性手动控制延迟加载的效果
  • fetchType="lazy(延迟加载)|eager(立即加载)"

分步查询的优点:

  • 可以实现延迟加载,必须在核心配置文件中设置全局配置信息(下划线映射驼峰)

第一步: 先查emp

    /**
     * 分布查询员工以及员工所对应的部门
     * 第一步:查询员工信息
     */
    Emp getEmpAndDeptByStepOne(@Param("empId")Integer empId);
    <resultMap id="empAndDeptByStepResultMap" type="emp">
        <id property="empId" column="emp_id"></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.xz.mapper.DeptMapper.getEmpAndDeptByStepTwo"
                     column="did"></association>
    </resultMap>
    <!-- Emp getEmpAndDeptByStepOne(@Param("empId")Integer empId);-->
    <select id="getEmpAndDeptByStepOne" resultMap="empAndDeptByStepResultMap">
        select * from t_emp where emp_id=#{empId}
    </select>

第二部:在查dept

    /**
     * 分布查询员工以及员工所对应的部门
     * 第二步:通过did查询员工所对应的部门
     */
    Dept getEmpAndDeptByStepTwo(@Param("deptId")Integer deptId);
   <select id="getEmpAndDeptByStepTwo" resultType="dept">
        select * from t_dept where dept_id=#{deptId}
    </select>

7.2.4延迟加载

  • lazyLoadingEnabled:延迟加载的全局开关。所有关联对象都会延迟加载(默认:false)
  • aggressiveLazyLoading:任何方法的调用都会加载该对象的所有属性(默认:false)
  • 可通过association和collection中的fetchType属性设置当前的分步查询是否使用延迟加载, fetchType="lazy(延迟加载)|eager(立即加载)"

延迟加载开启:获取去谁,就只会执行他所对应的sql语句!!!

   <!--设置Mybatis的全局配置-->
    <settings>
        <!--将下划线自动映射为驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>

7.3一对多映射

7.3.1collertion

collection:处理一对多的映射关系

ofType:标识该属性所对应的集合中存储数据的类型

<resultMap id="deptAndEmpResultMap" type="Dept">
        <id property="deptId" column="dept_id"></id>
        <result property="deptName" column="dept_name"></result>
        <collection property="emps" ofType="Emp">
            <id property="empId" column="emp_id"></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("empId") Integer empId);-->
    <select id="getDeptAndEmp" resultMap="deptAndEmpResultMap">
        select * from t_dept left join t_emp on t_dept.dept_id=t_emp.did where t_dept.dept_id=#{deptId}
    </select>
    /**
     * 部门以及部门所有的员工信息
     */
    Dept getDeptAndEmp(@Param("deptId") Integer deptId);

7.3.1collection分布查询

第一步:

    /**
     * 通过分布查询查询部门以及部门中所有的员工
     * 分布查询第一步
     */
    Dept getDeptAndEmpByStepOne(@Param("deptId")Integer deptId);
    <resultMap id="deptAndEmpByStepResultMap" type="dept">
        <id property="deptId" column="dept_id"></id>
        <result property="deptName" column="dept_name"></result>
        <collection property="emps"
                    select="com.xz.mapper.EmpMapper.getDeptAndEmpByStepTwo"
                    column="dept_id"></collection>
    </resultMap>
    
    <!--Dept getDeptAndEmpByStepOne(@Param("deptId")Integer deptId);-->
    <select id="getDeptAndEmpByStepOne" resultMap="deptAndEmpByStepResultMap">
        select * from t_dept where dept_id=#{deptId}
    </select>

第二步:

    /**
     * 通过分布查询查询部门以及部门中所有的员工
     * 第二步:根据did查询员工信息
     */
    List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);
   <!--List<Emp> getDeptAndEmpByStepTwo(@Param("empId") Integer empId);-->
    <select id="getDeptAndEmpByStepTwo" resultType="emp">
        select * from t_emp where did=#{did}
    </select>

8.动态SQL 🤶🤶🤶

Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决拼接SQL语句字符串时的痛点问题。

8.1if⭐⭐

  • if:根据标签中的test属性所对应的表达式决定标签中的内容是否需要拼接到sql中

 小技巧:where 后添加 1=1 恒成立条件!!!

    <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>

8.2where⭐⭐

  • where:动态生成where关键字
  • where标签中有内容时,会自动生成where关键字,并且将内容前多余的and或or去掉;
  • where标签中没有内容时,此时where没有任何效果

注意:where标签不能将其中内容后的and或or去掉

        <where>
            <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>
        </where> 

8.3trim

若标签中有内容时:

  • prefix,suffix:将trim标签中内容前面或后面添加指定内容
  • suffixOverrides,prefixOverrides:将trim标签中内容前面或后面删除指定内容

若标签中无内容时,trim标签没有任何效果!!!

   <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>

8.4choose,when,otherwise

相当于java中的if....else  if.....else

  • when至少有一个,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>

8.5foreach⭐⭐

foreach属性:

  1. collection:设置需要循环的数组或集合
  2. item:表示数组或集合中的每一个数据
  3. separator:循环体之间的分隔符
  4. open:foreach标签所循环的所有内容的开始符
  5. close:foreach标签所循环的所有内容的结束符

8.5.1批量删除

    /**
     * 通过数组实现批量删除
     */
    int deleteMoreByArray(@Param("empIds") Integer[] empIds);

方式一:

    <delete id="deleteMoreByArray">
        delete from t_emp where emp_id in
        <foreach collection="empIds" item="empId" separator="," open="(" close=")">
            #{empId}
        </foreach>
    </delete>

方式二:

    <delete id="deleteMoreByArray">
        delete from t_emp where
        <foreach collection="empIds" item="empId" separator="or">
            emp_id=#{empId}
        </foreach>
    </delete>

8.5.2批量添加 

    /**
     * 批量添加
     */
    int insertMoreByList(@Param("emps") List<Emp> emps);
   <!--int insertMoreByList(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>

8.6sql标签

  • <sql_ id="empColumns">emp_id,emp_name, age,sex,email</sql>:设置sql片段
  • <include refid="empColumns">:引用sql片段
  <sql id="empColumns">emp_id,emp_name,age,sex,email</sql>

    <!-- List<Emp> getEmpByCondition(Emp emp);-->
    <select id="getEmpByCondition" resultType="emp">
        select <include refid="empColumns"></include>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>

 

9.Mybatis缓存🤶🤶🤶

9.1Mybatis一级缓存

一级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取不会从数据库重新访问

使一级缓存失效的四种情况:

  1. 不同的SqlSession对应不同的一级缓存
  2. 同一个SqlSession但是查询条件不同 
  3. 同一个SqlSession两次查询期间执行了任何一次增删改操作
  4. 同一个SqlSession两次查询期间手动清空了缓存

一级缓存默认开启!!!

 9.1.1测试一级缓存

 Emp getEmpById(@Param("empId") Integer empId);
    <select id="getEmpById" resultType="emp">
        select * from t_emp where emp_id=#{empId}
    </select>

测试: 

  @Test
    public void getEmpById() {
        SqlSession session1 = SqlSessionUtils.getSession("mybatis-config.xml");
        CacheMapper mapper = session1.getMapper(CacheMapper.class);
        Emp emp1 = mapper.getEmpById(1);
        System.out.println(emp1);


        SqlSession session2 = SqlSessionUtils.getSession("mybatis-config.xml");
        CacheMapper mapper1 = session2.getMapper(CacheMapper.class);
        Emp emp2 = mapper1.getEmpById(1);
        System.out.println(emp2);
    }

 结果:

9.2Mybatis二级缓存

二级缓存是SqlSessionFactory级别,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取

二级缓存开启的条件:

  1. 在核心配置文件中,设置全局配置属性cacheEnabled="true",默认为true,不需要设置
  2. 在映射文件中设置标签<cache />
  3. 二级缓存必须在SqlSession关闭或提交之后有效
  4. 查询的数据所转换的实体类类型必须实现序列化的接口

使二级缓存失效的情况:两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效

1. 实体类类型必须实现序列化的接口:

2.开启标签cache:

3.SqlSession关闭或提交之后有效:

 @Test
    public void testTwoCache() throws IOException {
        InputStream resource = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resource);
        SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
        CacheMapper mapper = sqlSession1.getMapper(CacheMapper.class);
        Emp emp = mapper.getEmpById(1);
        System.out.println(emp);
        sqlSession1.close();

        SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
        CacheMapper mapper1 = sqlSession2.getMapper(CacheMapper.class);
        Emp emp1 = mapper1.getEmpById(1);
        System.out.println(emp1);
        sqlSession2.close();
    }

测试结果:

9.3二级缓存的配置

在mapper配置文件中添加的cache标签可以设置一些属性:

eviction属性:缓存回收策略

  • LRU (Least Recently Used) -最近最少使用的:移除最长时间不被使用的对象。
  • FIFO (First in First out) -先进先出:按对象进入缓存的顺序来移除它们。
  • SOFT- 软引用:移除基于垃圾回收器状态和软引用规则的对象。
  • WEAK - 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。默认的是 LRU。

flushInterval属性:刷新间隔,单位毫秒

  • 默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新

size属性:引用数目,正整数

  • 代表缓存最多可以存储多少个对象,太大容易导致内存溢出

readOnly属性:只读,true/false    此默认是 false。

  • true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。
  • false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因

9.4Mybatis缓存查询顺序

  1. 先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据
  2. 如果二级缓存没有命中再查询一级缓存
  3. 如果一级缓存也没有命中则查询数据库
  4. SqlSession关闭之后,一级缓存中的数据会写入二级缓存

9.5整合第三方缓存EHCache

添加依赖:

       <!--Mybatis EhCache整合包-->
        <dependency>
            <groupId>org.mybatis.caches</groupId>
            <artifactId>mybatis-ehcache</artifactId>
            <version>1.2.1</version>
        </dependency>

        <!--sl4j日志门面的具体体现-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"
        >

    <!--磁盘保存路径-->
    <diskStore path="F:\xz\ehcache"/>

    <defaultCache
            eternal="false"
            maxElementsInMemory="100000"
            overflowToDisk="true"
            diskPersistent="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            memoryStoreEvictionPolicy="LRU"/>

</ehcache>

设置二级缓存类型:

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

logback日志:

<?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.xz.mapper" level="DEBUG"/>-->
    <logger name="com.xz.mapper" level="DEBUG"/>
</configuration>

10.Mybatis逆向工程🤶🤶🤶

逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成如下资源:

  • Java实体类
  • Mapper接口
  • Mapper映射文件

10.1逆向工程插件:

  <!-- 控制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.33</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

10.2逆向工程的配置文件

文件名必须是:generationConfig.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="MyBatis3">
        <!-- 数据库的连接信息 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis"
                        userId="root"
                        password="123456">
            <property name="nullCatalogMeansCurrent" value="true"></property>
        </jdbcConnection>
        <!-- javaBean的生成策略
        enableSubPackages:是否使用子包  每个 . 对应一层目录
        trimStrings:去掉字符串前后的空格
        -->
        <javaModelGenerator targetPackage="com.xz.pojo" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- SQL映射文件的生成策略 -->
        <sqlMapGenerator targetPackage="com.xz.mapper"
                         targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- Mapper接口的生成策略 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.xz.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>

10.3逆向工程执行

10.4测试逆向工程

 10.4.1查询

查询全部(无条件):

List<Emp> emps = mapper.selectByExample(null);

根据条件查询:(QBC风格)

        EmpExample example = new EmpExample();
        example.createCriteria().andEmpNameEqualTo("张三").andAgeGreaterThanOrEqualTo(10);
        List<Emp> list = mapper.selectByExample(example);

11.分页插件🤶🤶🤶

11.1添加依赖

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>

11.2添加插件

设置在Mybatis的核心配置文件中!!!

    <!--设置分页插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

11.3使用插件

11.3.1使用Mybatis的分页插件实现分页步骤

1.查询之前开启分页:PageHelper.startPage( 3,2)

  • 3:表示当前页数
  • 2:表示每页显示的条数

2.查询功能之后获取分页相关信息:PageInfo<Emp> pageInfo=new PageInfo<>(emps, 5)

  • emps:表示分页数据。
  • 5:当前导航分页的数量
  @Test
    public void test() throws IOException {
        InputStream resource = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resource);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);

        PageHelper.startPage(3, 2);

        List<Emp> emps = mapper.selectByExample(null);

        PageInfo<Emp> pageInfo=new PageInfo<>(emps,5);
        System.out.println(pageInfo);
        
    }

11.3.2分页查询的结果

PageInfo{pageNum=3, pageSize=2, size=2, startRow=5, endRow=6, total=11, pages=6, list=Page{count=true, pageNum=3, pageSize=2, startRow=4, endRow=6, total=11, pages=6, reasonable=false, pageSizeZero=false}[Emp{empId=9, empName='jj', age=12, sex='男', email='11qq.com', did=null}, Emp{empId=10, empName='kk', age=22, sex='男', email='22qq.com', did=null}], prePage=2, nextPage=4, isFirstPage=false, isLastPage=false, hasPreviousPage=true, hasNextPage=true, navigatePages=5, navigateFirstPage=1, navigateLastPage=5, navigatepageNums=[1, 2, 3, 4, 5]}

常用数据含义:

  • pageNum:当前页的页码
  • pageSize:每页显示的条数
  • size:当前页显示的真实条数
  • startRow:从第几行开始
  • endRow:从第几行结束
  • total:总记录数
  • pages:总页数
  • prePage:上一页的页码
  • nextPage:下一页的页码
  • isFirstPage/isLastPage:是否为第一页/最后一页
  • hasPreviousPage/hasNextPage:是否存在上一页/下一页
  • navigatePages:导航分页的页码数
  • navigatepageNums:导航分页的页码,[1,2,3,4,5]

​​​​​​​

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会敲代码的小张

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值