SSM学习笔记----Mybatis

SSM框架及其整合
在这里插入图片描述
在这里插入图片描述

SSM

一、Mybatis

Ⅰ、Mybatis简介

1.Mybatis历史
  • MyBatis最初是Apache的一个开源项目iBatis, 2010年6月这个项目由Apache Software Foundation迁移到了Google Code。随着开发团队转投Google Code旗下,iBatis3.x正式更名为MyBatis。代码于2013年11月迁移到Github。
  • iBatis一词来源于"internet"和"abatis""的组合,是一个基于Java的持久层框架。iBatis提供的持久层框架包括SQL Maps和Data Access Objects (DAO)。
2.Mybatis特性
  • MyBatis是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架

  • MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集

  • MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和ava的POJo(Plain Old Javaobjects,普通的Java对象)映射成数据库中的记录

  • MyBatis 是一个半自动的ORM (Object Relation Mapping)框架

3.Mybatis下载

下载地址:https://github.com/mybatis

在这里插入图片描述

4.Mybatis与其他持久层技术对比
  • JDBC
    • SQL夹杂在ava代码中耦合度高,导致硬编码内伤
    • 维护不易且实际开发需求中SQL有变化,频繁修改的情况多见
    • 代码冗长,开发效率低
  • Hilbernate和JPA
    • 操作简便,开发效率高
    • 程序中的长难复杂SQL需要绕过框架
    • 内部自动生产的SQL,不容易做特殊优化
    • 基于全映射的全自动框架,大量字段的POJO进行部分映射时比较困难。
    • 反射操作太多,导致数据库性能下降
  • Mybatis
    • 轻量级,性能出色
    • SQL和Java编码分开,功能边界清晰。Java代码专注业务、SQL语句专注数据
    • 开发效率稍逊于Hlbernate,但是完全能够接受

Ⅱ、搭建Mybaties

1.开发环境
2、创建maven项目
①打包方式:jar
②引入依赖
<!--    打包方式-->
    <packaging>jar</packaging>
    <!-- 导入依赖   -->
    <dependencies>
    <!--     mybatis核心   -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</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.31</version>
        </dependency>
3、创建Mybatis的核心配置文件

作用:用于配置连接数据库的环境以及Mybatis的全局配置信息

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
 <environments default="development">
 <environment id="development">
 <transactionManager type="JDBC"/>
 <dataSource type="POOLED">
 <property name="driver" value="${driver}"/>
 <property name="url" value="${url}"/>
 <property name="username" value="${username}"/>
 <property name="password" value="${password}"/>
 </dataSource>
 </environment>
 </environments>
 <mappers>
 <mapper resource="org/mybatis/example/BlogMapper.xml"/>
 </mappers>
</configuration>
4、创建mapper接口

mapper======>dao mapper:仅仅为接口,不需要提供实现类

public interface UserMapper {
    int insertUser();
}
5、创建Mybatis映射文件

ORM:(object relationship mapping)对象关系映射

  • 对象:java实体类对象
  • 关系:关系型数据库
  • 映射:二者之间的对应关系
java概念数据库概念
属性字段/列
对象记录/行
  • 一个映射文件对应一个实体类,对应一张表的操作

两个一致:

  • a---->mapper 接口全类名和映射文件的命名空间(namespace相同)保持一致
  • b------>mapper接口中方法的方法名和映射文件中编写SQL的标签的id属性保持一致

UserMapper:

<?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.lyj.mybatis.mapper.UserMapper">
     <!--  int insertUser();   -->
    <insert id="insertUser">
        insert into t_user value (1,'admin','1234','23','男','2132312@qq.com')
    </insert>
</mapper>
public void test() throws IOException {
        //获取核心配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        //获取SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //获取SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
        //获取sql会话对象SqlSession,Mybatis提供的操作数据库对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //自动提交事务
        //SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
        //获取UserMapper的代理实现类对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用mapper接口中方法
        int i = mapper.insertUser();
        System.out.println("结果:" + i);
        //需要手动提交事务
        sqlSession.commit();
        //关闭
        sqlSession.close();
    }

在这里插入图片描述

6、加入log4j功能
①导入依赖
      <!--   加入log4j日志     -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

文件名必须是 log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
                     xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                   value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
        </layout>
    </appender>

    <appender name="file" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false" />
        <param name="maxFileSize" value="10MB" />
        <param name="maxBackupIndex" value="10" />
        <param name="file" value="${catalina.home}/logs/my.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                   value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
        </layout>
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="console" />
        <appender-ref ref="file" />
    </root>

</log4j:configuration>

②日志输出

在这里插入图片描述

FATAL(致命)----->ERROR(错误)------>WARN(警告)---->INFO(信息)----->DEBUG(调试)

ender-ref ref=“console” />

</log4j:configuration>


##### ②日志输出

[外链图片转存中...(img-LWdejmuS-1685798304812)]

FATAL(致命)----->ERROR(错误)------>WARN(警告)---->INFO(信息)----->DEBUG(调试)
### Ⅲ、核心配置文件

##### ①environments

~~~xml
<!--
    environments:配置连接数据库的环境
    default:设置默认使用环境id,
    environment:设置一个具体的连接数据库的环境,
                 属性id,设置环境唯一标识,
    transactionManager:设置事务管理方式,
                        type:事务管理方式  === JDBC  ||  MANAGED
                        JDBC:jdbc原生管理方式
                        MANAGED:被管理,例如Spring
    dataSource:设置数据源
                type:设置数据源类型
                type= POOLED | UNPOOLED | JNDI
                POOLED:使用数据库连接池
                UNPOOLED:不使用数据库连接池
                JNDI:使用上下文中的数据源
  -->
②properties
    <!-- 引入properties文件,此后可以在当前文件中使用${key}访问value   -->

③typeAliases
  <!--
      Mybatis核心配置文件中标签需按照指定顺序配置
      (properties?,settings?,typeAliases?,
      typeHandlers?,objectFactory?,
      objectWrapperFactory?,reflectorFactory?,
      plugins?,environments?,
      databaseIdProvider?,mappers?)".
      -->
    <!--
       typeAliases:设置类型别名,即为某个具体的类型设置别名
       在Mybatis的范围中,可以使用别名表示一个具体的类型
                   type:设置需要起别名的类型
                   alias:设置某一个类型的别名,默认为类名,且不区分大小
        package:通过包名设置类型别名,指定包下所有的类型全部拥有默认的别名
      -->
④mappers
  <!--
      package:以包的方式引入映射文件,需满足两个条件
      mapper接口和映射文件所在包一致
      mapper接口名字与映射文件名字一致
      -->

Ⅳ、Mybatis获取参数

  • MyBatis获取参数值的两种方式: ${}#{}
  • ${} 的本质就是字符串拼接,#{} 的本质就是占位符赋值
  • ${} 使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字
  • 进行赋值时,需要手动加单引号;但是 #{} 使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号
1、单个字面量类型的参数
  • 若mapper接口中的方法参数为单个的字面量类型:此时可以使用 ${} 和 #{} 以任意的名称获取参数的值,注意 ${} 需要手动加单引号
2、多个字面量类型的参数

若mapper接口中的方法参数为多个时:

  • 此时MyBatis会自动将这些参数放在一个map集合中,以arg0,arg1…为键,以参数为值;

  • 以param1,param2…为键,以参数为值;因此只需要通过 ${} 和 #{} 访问map集合的键就可以获取相对应的值,注意 ${} 需要手动加单引号

3、map集合类型的参数

若mapper接口中的方法参数为map集合时:

  • 只需要通过 #{} 和 ${} 访问map集合的键,就可以获取相应的值,
  • 注意:${} 单引号问题
4、实体类类型的参数

若mapper接口方法的参数为实体类类型的参数

  • 只需要通过 #{} 和 ${} 访问实体类中的属性名,就可以获取相应的值
  • 注意:${} 单引号问题
5、 @param 注解标识 参数

可以在mapper接口方法的参数上设置 @param 注解

  • 此时mybatis会将这些参数放入map中,以两种方式存储

  • 以@param注解的value属性值为键,以参数为值

  • 以param1,param2…为键,以参数为值

Ⅴ、Mybatis查询功能

1、查询一个实体类对象
//根据id查询用户信息
    User getUserById();
  <!--    //根据id查询用户信息
    User getUserById();-->
    <select id="getUserById" resultType="com.lyj.mybatis.pojo.User1">
        select * from t_user where id=1
    </select>

2、查询一个list集合
//若sql语句查询结果为多条时,不能以实体类型为返回值
//当查询数据只有一条,可以使用实体类型或集合作为返回值
//若sql语句查询结果为1时,此时可以使用实体类类型或list类型作为方法返回值
//查询所有用户信息
    List<User1> getAllUser();
 <select id="getAllUser" resultType="User1">
        select * from t_user
    </select>
3、查询单个数据
//查询用户总数量
    Integer getCount();
<select id="getCount" resultType="java.lang.Integer">
        select count(*) from t_user
    </select>
4、查询一条数据为map集合
//根据id查询用户信息为map集合
    Map<String,Object> getUserByIdToMap(@Param("id") Integer id);
 <select id="getUserByIdToMap" resultType="map">
        select *
        from t_user
        where id=#{id}
    </select>
5、查询多条数据为map集合
①方式一
//查询所有的用户信息为Map集合
    List<Map<String,Object>> getAllUserToMap();    
②方式二
//map集合放入一个大的map中,以某个字段的参数为大map的键,
    @MapKey("id")
    Map<String,Object> getAllUserToMap();
<!--    //查询所有的用户信息为Map集合
    Map<String,Object> getAllUserToMap();-->
    <select id="getAllUserToMap" resultType="map">
        select *
        from t_user
    </select>

Ⅵ、特殊SQL的执行

1、模糊查询
//通过用户名模糊查询用户信息
    List<User1> getUserByLike(@Param("mohu")String mohu);

字符串拼接:

select *
            from t_user
            where username Like concat('%'+#{mohu}+'%')

使用${} 取值

select *
--         from t_user
--         where username Like '%${mohu}%'

使用 “”#{}“”

select * from t_user where username Like "%"#{mohu}"%"
2、批量删除
    //批量删除
    void deleteMoreUser(@Param("ids")String ids);
  <delete id="deleteMoreUser">
        delete from t_user where id in(${ids})
    </delete>

若使用 #{} :

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fksJP58p-1686231365739)(SSM.assets/image-20230605203243543.png)]

3、动态设置表名
  //动态设置表名,查询用户信息
    List<User1> getUserList(@Param("tableName") String tableName);
<select id="getUserList" resultType="User1">
        select * from ${tableName}
    </select>
4、添加功能获取自增的主键

场景模拟:
t_clazz(clazz_id,clazz_name)
t_student(student_id,student_name,clazz_id)

  • 添加班级信息
  • 获取新添加的班级的id
  • 为班级分配学生,即将某学的班级id修改为新添加的班级的id
//添加用户信息,获取自增主键
    void insertUser(User1 user1);
<!-- //添加用户信息,获取自增主键
      void insertUser(User1 user1);
      useGeneratedKeys="true"  :获取自增主键
      keyProperty="id"   :主键属性
      -->
    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
        insert into t_user values (null,#{username},#{password},#{age},#{gender},#{email})
    </insert>

Ⅶ、自定义映射resultMap

1、resultMap处理字段和属性的映射关系

若字段名和实体类中的属性名不一致,则可以通过resultMap设置自定义映射

Emp getEmpByEmpId(@Param("empId")Integer empId);

核心配置文件需添加

<settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
<!--
    Emp getEmpByEmpId(@Param("empId")Integer empId);

    字段名和属性名不一致:
    1、为查询字段设置别名与属性名保持一致
    2、当字段符合mysql要求,使用下划线,属性符合java驼峰规则
       可以在mybatis核心配置文件中设置全局配置,可将下划线映射为驼峰
       emp_id====empId
       emp_name===empName
-->
    <select id="getEmpByEmpId" resultType="Emp">
      <!--  select emp_id empId,emp_name empName,emp_gender empGender,emp_age empAge from t_emp where emp_id=#{empId}  -->
        select * from t_emp where emp_id=#{empId}
    </select>
2、多对一映射处理
①级联处理
<resultMap id="EmpAndDeptByEmpIdOne" type="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="emp_age" property="empAge"></result>
        <result column="emp_gender" property="empGender"></result>
        <result column="dept_id" property="dept.deptId"></result>
        <result column="dept_name" property="dept.deptName"></result>
    </resultMap>
<select id="getEmpAndDeptByEmpId" resultMap="EmpAndDeptByEmpIdOne"  >
        select *
        from t_emp
            left join t_dept on t_emp.dept_id=t_dept.dept_id
        where t_emp.emp_id=#{empId};
    </select>
②使用association标签
    <resultMap id="EmpAndDeptByEmpIdTwo" type="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="emp_age" property="empAge"></result>
        <result column="emp_gender" property="empGender"></result>
        <result column="dept_id" property="dept.deptId"></result>

        <!--
            association:处理多对一的映射关系(处理实体类类型属性)
            property:需处理映射关系的属性的属性名
            javaType:要处理属性类型
        -->
        
        <association property="dept" javaType="Dept">
            <id column="dept_id" property="deptId"></id>
            <result column="dept_name" property="deptName"></result>
        </association>
    </resultMap>
<select id="getEmpAndDeptByEmpId" resultMap="EmpAndDeptByEmpIdTwo"  >
        select *
        from t_emp
            left join t_dept on t_emp.dept_id=t_dept.dept_id
        where t_emp.emp_id=#{empId};
    </select>
3、分布查询
①查询员工信息
 //分布查询员工与对应部门信息
    //第一步
    Emp getEmpAndDeptByStepOne(@Param("empId") Integer empId);

<!--      //分布查询员工与对应部门信息
    //第一步
    Emp getEmpAndDeptByStepOne(@Param("empId") Integer empId);
      -->

<!--
      property:需处理映射关系的属性的属性名
      select:设置下一分布查询sql唯一标识
      column:将查询出的某一个字段作为分布查询的sql条件
-->
    <resultMap id="EmpAndDeptByStepResultMap" type="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="emp_age" property="empAge"></result>
        <result column="emp_gender" property="empGender"></result>
        <result column="dept_id" property="dept.deptId"></result>
        <association property="dept"
                     select="com.lyj.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
                     column="dept_id">
        </association>
    </resultMap>

    <select id="getEmpAndDeptByStepOne" resultMap="EmpAndDeptByStepResultMap">
        select *
        from t_emp where emp_id=#{empId};
    </select>

②根据员工dept_id查部门信息
//分布查询员工与对应部门信息
    //第二步:根据
    Dept getEmpAndDeptByStepTwo(@Param("deptId") Integer deptId);
<!--  //分布查询员工与对应部门信息
    //第二步:根据
    Dept getEmpAndDeptByStepTwo(@Param("deptId") Integer deptId);
  -->
    <select id="getEmpAndDeptByStepTwo" resultType="Dept">
        select * from t_dept where dept_id=#{deptId};
    </select>
4、一对多映射处理
①通过collection
//查询部门及部门中的员工信息
    Dept getDeptAndEmpByDeptId(@Param("deptId") Integer deptId);
<!--  //查询部门及部门中的员工信息
    Dept getDeptAndEmpByDeptId(@Param("deptId") Integer deptId);
    collection:处理一对多的映射关系(处理集合类型的属性)
    property:property:需处理映射关系的属性的属性名
    ofType:设置集合类型的属性中存储的数据的类型
  -->
    <resultMap id="deptAndEmpResultMap" type="Dept">
        <id column="dept_id" property="deptId"></id>
        <result column="dept_name" property="deptName"></result>
        <collection property="empList" ofType="Emp">
            <id column="emp_id" property="empId"></id>
            <result column="emp_name" property="empName"></result>
            <result column="emp_age" property="empAge"></result>
            <result column="emp_gender" property="empGender"></result>
        </collection>
    </resultMap>

    <select id="getDeptAndEmpByDeptId" resultMap="deptAndEmpResultMap">
        select * from t_dept left join  t_emp on
            t_dept.dept_id=t_emp.dept_id where t_dept.dept_id=#{deptId}
    </select>
②分布查询
  //分布查询部门及部门中员工信息第一步
    Dept getDeptAndEmpByStepOne(@Param("deptId") Integer deptId);
//分布查询部门与员工信息,第二步
    List<Emp> getDeptAndEmpByStepTwo(@Param("deptId") Integer deptId);
<!--  //分布查询部门及部门中员工信息第一步
    Dept getDeptAndEmpByStepOne(@Param("deptId") Integer deptId);
  -->
    <resultMap id="deptAndEmpResultMapByStep" type="Dept">
        <id column="dept_id" property="deptId"></id>
        <result column="dept_name" property="deptName"></result>
        <collection property="empList" select="com.lyj.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo" column="dept_id"></collection>
    </resultMap>
    <select id="getDeptAndEmpByStepOne" resultMap="deptAndEmpResultMapByStep">
        select *
        from t_dept
        where dept_id=#{deptId};
    </select>
<!-- //分布查询部门与员工信息,第二步
    List<Emp> getDeptAndEmpByStepTwo(@Param("deptId") Integer deptId);
   -->
    <select id="getDeptAndEmpByStepTwo" resultType="Emp">
        select * from t_emp where dept_id=#{deptId};
    </select>

分布查询优点 可以实现延迟加载

  • 但是必须在核心配置文件中设置全局配置信息:
    lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载
  • aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属性会按需加载
    此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql。此时可通过associationcollection中的fetchType属性设置当前的分步查询是否使用延迟加载, fetchType="“lazy(延迟加载)|eager(立即加载)”

Ⅷ、动态SQL

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

1、if

if标签可通过test属性的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行

<!--    //根据条件查询员工信息
    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="empAge != null and empAge != '' ">
            and emp_age=#{empAge}
        </if>
    </select>
2、where
  • 若where标签中有条件成立,会自动生成where关键字
  • 会自动将内容前多余的and去掉,但是其中内容后多余的and无法去掉
  • 若where标签中没有任何条件成立,则where标签没有任何功能
    <select id="getEmpByCondition" resultType="Emp">
        select * from t_emp
        <where>
            <if test="empName !=null and empName != ''">
                emp_name=#{empName}
            </if>

            <if test="empAge != null and empAge != '' ">
                and emp_age=#{empAge}
            </if>
        </where>
    </select>
3、trim
  • prefix,suffix:在标签中内容前或后面添加指定内容
  • prefixOverrides,suffixOverrides,在标签中内容前或标签中内容后去掉某些内容
    <select id="getEmpByCondition" resultType="Emp">
        select * from t_emp
        <trim prefix="where" suffixOverrides="and">
            <if test="empName !=null and empName != ''">
                emp_name=#{empName}
            </if>

            <if test="empAge != null and empAge != '' ">
                and emp_age=#{empAge}
            </if>
        </trim>
4、choose、when、otherwise
  • 相当于java中if…else if… else
  • when 至少一个
  • otherwise 至多一个
<!--
       //使用choose查询
    List<Emp> getEmpByChoose(Emp emp);
   -->

    <select id="getEmpByChoose" resultType="Emp">
        select * from t_emp
        <where>
            <choose>
                <when test="empName !=null and empName !='' ">
                    emp_name=#{empName}
                </when>

                <when test="empAge != null and empAge != '' ">
                    emp_age=#{empAge}
                </when>

                <when test="empGender != null and empGender != '' ">
                    emp_gender=#{empGender}
                </when>

            </choose>
        </where>
    </select>
5、foreach
  • collection:设置要循环的数组或集合
  • item:用一个字符串表示数组或集合中的每一个数据
  • separator:设置每次循环的数据之间的分隔符
  • open:循环内容以什么开始
  • close:循环内容以什么结束
①批量添加
    //批量添加信息
    void insertMoreEmp(@Param("empList") List<Emp> empList);
<!--     //批量添加信息
    void insertMoreEmp(List<Emp> empList);   -->
    <insert id="insertMoreEmp" >
        insert into t_emp values
        <foreach collection="empList" item="emp" separator=",">
            (null,#{emp.empName},#{emp.empAge},#{emp.empGender},null)
        </foreach>
    </insert>
②批量删除
    //批量删除
    void deleteMoreEmp(@Param("empIds") Integer[] empIds);

<!--      //批量删除
    void deleteMoreEmp(@Param("empIds") Integer[] empIds);
-->

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

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

    </delete>
6、sql片段

可以记录一端sql,需要使用时用include引用

    <sql id="empColumns">
        emp_id,emp_name,emp_age,emp_gender,dept_id
    </sql>
    <select id="getEmpByCondition" resultType="Emp">
        select <include refid="empColumns"></include> from t_emp where
        <if test="empName !=null and empName != ''">
            emp_name=#{empName}
        </if>

        <if test="empAge != null and empAge != '' ">
            and emp_age=#{empAge}
        </if>

        <if test="empGender != null and empGender != '' ">
            and emp_gender=#{empGender}
        </if>

    </select>

Ⅸ、Mybatis缓存

1、mybatis一级缓存

—级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取,不会从数据库重新访问
使━级缓存失效的四种情况:

  • 不同的SqISession对应不同的一级缓存
  • 同一个SqlSession但是查询条件不同
  • 同一个SqlSession两次查询期间执行了任何一次增删改操作
  • 同一个SqlSession两次查询期间手动清空了缓存sqlSession.clearCache()
2、mybatis二级缓存

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

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

使二级缓存失效的情况:

  • 两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效
3、二级缓存相关配置

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

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

  • flushInterval属性:刷新间隔,单位毫秒。默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新

  • ③size属性:引用数目,正整数。代表缓存最多可以存储多少个对象,太大容易导致内存溢出

  • ④readOnly属性:只读,true/false

    true:只读缓存,会给所有调用者返回缓存对象的相同实例,因此这些对象不能被修改,提供了重要的性能优势

    false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false。

4、mybatis缓存查询的顺序

先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用。

如果二级缓存没有命中,再查询一级缓存
如果一级缓存也没有命中,则查询数据库
SqlSession关闭之后,—级缓存中的数据会写入二级缓存

5、整合第三方缓存EHCache
①添加依赖
 <!--   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>
②创键EHCache的配置文件ehcache.xml

注:文件名必须为ehcache.xml

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

    <!--diskStore: 持久化到磁盘上时的存储位置-->
    <diskStore path="D:\lyj\ehcache"/>

    <!--
      name:缓存名称。
      maxElementsInMemory:缓存最大个数。
      eternal:对象是否永久有效,一但设置了,timeout将不起作用。
      timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
      timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
      overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
      diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
      maxElementsOnDisk:硬盘最大缓存个数。
      diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
      diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
      memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
      clearOnFlush:内存数量最大时是否清除。
   -->

    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
    />

    <cache
            name="cacheSpace"
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
    />

</ehcache>

③设置二级缓存类型
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
④加入logback日志

存在SLF4时,作为简易日志的log4j将失效,此时,需要借助SLF4的具体实现logback来打印日志。

logback的配置文件是logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true"
               scanPeriod="60 seconds"
               debug="false">

    <!-- 应用名称:和统一配置中的项目代码保持一致(小写) -->
    <property name="APP_NAME" value="app"/>
    <contextName>${APP_NAME}</contextName>
    <!--日志文件保留天数 -->
    <property name="LOG_MAX_HISTORY" value="30"/>
    <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径 -->

    <!--应用日志文件保存路径 -->
    <!--在没有定义${LOG_HOME}系统变量的时候,可以设置此本地变量。 -->
    <property name="LOG_HOME" value="logs"/>
    <property name="INFO_PATH" value="${LOG_HOME}/info"/>
    <property name="DEBUG_PATH" value="${LOG_HOME}/debug"/>
    <property name="ERROR_PATH" value="${LOG_HOME}/error"/>
    <!--<property name="LOG_HOME" msg="/home/logs/${APP_NAME}" />-->

    <!--=========================== 按照每天生成日志文件:默认配置=================================== -->
    <!-- 控制台输出 -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%c类名,%t表示线程名,%L行, %p日志级别 %msg:日志消息,%n是换行符  -->
            <pattern>%black(%contextName - %d{yyyy-MM-dd HH:mm:ss}) %green([%c][%t][%L]) %highlight(%-5level) - %gray(%msg%n)</pattern>
        </encoder>
    </appender>

    <!-- 按照每天生成日志文件:主项目日志 -->
    <appender name="APP_DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名 -->
            <FileNamePattern>${DEBUG_PATH}/debug-%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数 -->
            <MaxHistory>${LOG_MAX_HISTORY}</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%c类名,%t表示线程名,%L行, %p日志级别 %msg:日志消息,%n是换行符  -->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%c][%t][%L][%p] - %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <!-- 此日志文件只记录debug级别的 -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>debug</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <!-- 按照每天生成日志文件:主项目日志 -->
    <appender name="APP_INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名 -->
            <FileNamePattern>${INFO_PATH}/info-%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数 -->
            <MaxHistory>${LOG_MAX_HISTORY}</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%c类名,%t表示线程名,%L行, %p日志级别 %msg:日志消息,%n是换行符  -->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%c][%t][%L][%p] - %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>

        <!-- 此日志文件只记录info级别的 -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>info</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <!-- 按照每天生成日志文件:主项目日志 -->
    <appender name="APP_ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名 -->
            <FileNamePattern>${ERROR_PATH}/error-%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数 -->
            <MaxHistory>${LOG_MAX_HISTORY}</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%c类名,%t表示线程名,%L行, %p日志级别 %msg:日志消息,%n是换行符  -->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%c][%t][%L][%p] - %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <!-- 此日志文件只记录error级别的 -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>error</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <!--日志输出到文件-->
    <root level="info">
        <appender-ref ref="APP_DEBUG"/>
        <appender-ref ref="APP_INFO"/>
        <appender-ref ref="APP_ERROR"/>
        <appender-ref ref="console"/>
    </root>

    <!-- mybatis 日志级别 -->
    <logger name="com.pm.health" level="debug"/>
</configuration>


⑤配置说明
 <!--
      name:缓存名称。
      maxElementsInMemory:缓存最大个数。
      eternal:对象是否永久有效,一但设置了,timeout将不起作用。
      timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
      timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
      overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
      diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
      maxElementsOnDisk:硬盘最大缓存个数。
      diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
      diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
      memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
      clearOnFlush:内存数量最大时是否清除。
   -->

Ⅹ、Mybatis逆向工程

正向工程:创建java实体类,由框架负责根据实体类生成数据库表

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

  • java实体类
  • Mapper接口
  • Mapper映射文件
步骤:
①导入依赖
<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>
        <!--  log4j日志      -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    
    <!-- Mysql驱动 -->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.31</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>


                    <!-- Mysql驱动 -->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.31</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
②mybatis核心配置
<?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文件,此后可以在当前文件中使用¥{key}访问value   -->
    <properties resource="jdbc.properties"></properties>

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!--
      Mybatis核心配置文件中标签需按照指定顺序配置
      (properties?,settings?,typeAliases?,
      typeHandlers?,objectFactory?,
      objectWrapperFactory?,reflectorFactory?,
      plugins?,environments?,
      databaseIdProvider?,mappers?)".
      -->

    <!-- 类型别名   -->
    <typeAliases>
        <package name="com.lyj.mybatis.pojo"/>
    </typeAliases>

    <!--  开发环境  -->
    <!--
    environments:配置连接数据库的环境
    default:设置默认使用环境id,
    environment:设置一个具体的连接数据库的环境,
                 属性id,设置环境唯一标识,
    transactionManager:设置事务管理方式,
                        type:事务管理方式  === JDBC  ||  MANAGED
                        JDBC:jdbc原生管理方式
                        MANAGED:被管理,例如Spring
    dataSource:设置数据源
                type:设置数据源类型
                type= POOLED | UNPOOLED | JNDI
                POOLED:使用数据库连接池
                UNPOOLED:不使用数据库连接池
                JNDI:使用上下文中的数据源
  -->
    <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>


    <!--  引入Mybatis映射文件  -->
    <!--
      package:以包的方式引入映射文件,需满足两个条件
      mapper接口和映射文件所在包一致
      mapper接口名字与映射文件名字一致
      -->
    <mappers>
        <package name="com.lyj.mybatis.mapper"/>
    </mappers>
</configuration>
③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>

    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包 -->
    <!--
    <classPathEntry  location="D:\maven-warehouse\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar"/>
    -->
    <!-- <classPathEntry  location="D:\maven-warehouse\repository\mysql\mysql-connector-java\8.0.17\mysql-connector-java-8.0.17.jar"/> -->



<!--
      targetRuntime:执行生成的逆向工程的版本
      Mybatis3Simple:生成基本的CRUD
      Mybatis3:生成带条件的CRUD
-->


    <context id="DB2Tables"  targetRuntime="MyBatis3Simple">
        <!-- 实体类生成序列化属性-->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
        <!-- 实体类重写HashCode()和equals()-->
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" />
        <!-- 实体类重写toString() -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />

        <commentGenerator>
            <!-- 是否去除自动生成的注释 -->
            <property name="suppressAllComments" value="false"/>
            <!-- 生成注释是否带时间戳-->
            <property name="suppressDate" value="true"/>
            <!-- 生成的Java文件的编码格式 -->
            <property name="javaFileEncoding" value="utf-8"/>
            <!-- 格式化java代码-->
            <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter" />
            <!-- 格式化XML代码-->
            <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter" />
        </commentGenerator>

        <!-- 数据库连接驱动类,URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/ssm?useUnicode=true&amp;characterEncoding=UTF-8"
                        userId="root" password="admin">
        </jdbcConnection>

        <!-- java类型处理器:处理DB中的类型到Java中的类型 -->
        <javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
            <!-- 是否有效识别DB中的BigDecimal类型 -->
            <property name="forceBigDecimals" value="true"/>
        </javaTypeResolver>

        <!-- 生成Domain模型:包名(targetPackage)、位置(targetProject) -->
        <javaModelGenerator targetPackage="com.lyj.mybatis.pojo" targetProject=".\src\main\java">
            <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
            <property name="enableSubPackages" value="true"/>
            <!-- 设置是否在getter方法中,对String类型字段调用trim()方法-->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 生成xml映射文件:包名(targetPackage)、位置(targetProject) -->
        <sqlMapGenerator targetPackage="com.lyj.mybatis.mapper" targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!--Mapper接口生成策略-->
        <!-- 生成DAO接口:包名(targetPackage)、位置(targetProject) -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.lyj.mybatis.mapper" targetProject=".\src\main\java">
            <!--是否使用子包-->
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!--逆向分析的表-->
        <!-- 要生成的表:tableName - 数据库中的表名或视图名,domainObjectName - 实体类名 -->
        <!--
        <table tableName="tableName" domainObjectName="tableNameDO"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
        -->
        <table tableName="t_emp" domainObjectName="Emp"/>
        <table tableName="t_dept" domainObjectName="Dept"/>

    </context>
</generatorConfiguration>

Ⅺ、分页插件

sql语句:limit index pageSize

index:当前页起始索引 index = (pageBum-1)*pageSize

pageSize:每页显示条数

pageNum:当前页页码

count:总记录数

totalPage:总页数 count / pageSize

1、步骤
①导入依赖
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>
②配置分页插件

在mybatis核心配置文件中配置插件

    <!--配置分页插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
  • pageNum:当前页的页码
  • pageSize:每页显示的条数
  • size:当前页显示的真实条数
  • total:总记录数
  • pages:总页数
  • prePage: 上一页的页码
  • nextPage: 下一页的页码
  • isFirstPage/isLastPage:是否为第一页/最后—页
  • hasPreviousPage/hasNextPage:是否存在上—页/下一页
  • navigatePages:导航分页的页码数
  • navigatepageNums:导航分页的页码,[1,2,3,4,5]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值