mybatis

一、搭建环境

1、创建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"/>
    <!--
        environments设置连接数据库的环境
        属性:
        default:设置默认使用的环境id
    -->
    <environments default="development">
        <!--
            environment:设置一个具体的连接数据库的环境
            属性:
            id:设置环境的唯一标识,不能重复
        -->
        <environment id="development">
            <!--
                transactionManager:设置事务管理器
                属性:
                type:设置事务管理的方式 "JDBC/MANAGED"
                    -JDBC:表示使用JDBC中原生的事务管理方式(可以自动提交事务,可以手动提交)
                    -MANAGED:被管理,例如Spring
                dataSource:设置数据源
                属性:
                type:设置数据源的类型 "POOLED/"
                    -POOLED:使用数据库连接池
                    -UNPOOLED:不使用数据库连接池,每次重新创建连接
                    -JNDI表示使用上下文中的数据源
            -->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入mybatis映射文件-->
    <mappers>
        <mapper resource="mappers/UserMapper.xml"/>
    </mappers>
</configuration>
2、创建mapper接口

MyBatis中的mapper接口相当于以前的dao。但是区别在于,mapper仅仅是接口,我们不需要提供实现类。通过mybatis里面的功能,为他创建一个代理实现类,当我们调用接口中的方法,就直接对应一个sql语句。
一个mapper接口对应一个sql语句。

public interface UserMapper {
	/**
	* 添加用户信息
	*/
	int insertUser();
}
3、MyBatis的映射文件

ORM(Object Relationship Mapping)对象关系映射。

  • 对象:Java的实体类对象
  • 关系:关系型数据库
  • 映射:二者之间的对应关系
    在这里插入图片描述
    1、映射文件的命名规则:
    表所对应的实体类的类名+Mapper.xml
    例如:表t_user,映射的实体类为User,所对应的映射文件为UserMapper.xml
    因此一个映射文件对应一个实体类,对应一张表的操作
    MyBatis映射文件用于编写SQL,访问以及操作表中的数据
    MyBatis映射文件存放的位置是src/main/resources/mappers目录下

2、 MyBatis中可以面向接口操作数据,要保证两个一致:

  • mapper接口的全类名和映射文件xml的命名空间(namespace)保持一致
  • mapper接口中方法的方法名和映射文件中编写SQL的标签的id属性保持一致
4、测试添加功能
package com.atuguigu.mybatis.test;

import com.atguigu.mybatis.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisTest {
    @Test
    public void testInsert() throws IOException {
        //获取核心配置文件输入流
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        //获取SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //获取sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        // 获取sql的会话对象sqlSession,是MyBatis提供的操作数据库的对象
        创建SqlSession对象,若没有设置true,此时通过SqlSession对象所操作的sql都必须手动提交或回滚事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //获取UserMapper的代理实现类  代理模式创建当前接口的代理实现类并找到sql语句
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用Mapper接口中的方法,实现添加用户信息的功能
        int res = mapper.insertUser();
        System.out.println("res = " + res);
        //提交事务
        //sqlSession.commit();
        //关闭sqlSession对象
        sqlSession.close();

    }

}

5、日志功能log4j

日志的级别:FATAL(致命)>ERROR(错误)>WARN(警告)>INFO(信息)>DEBUG(调试)
从左到右打印的内容越来越详细
src\main\java\resources\log4j.xml

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

pom.xml加入依赖

<!-- log4j日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
7、查询功能

查询功能映射xml需要提供resultType或者resultMap(二者只能设置一个)

  • resultType:设置结果类型,即查询的数据要转换为的java类型
  • resultMap:自定义映射,处理多对一或一对多的映射关系
    <!-- User getUser();-->
    <select id="getUser" resultType="com.atguigu.mybatis.pojo.User">
        select * from t_user where id = 1
    </select>
8、类型别名

MyBatis核心配置文件中,标签的顺序:
properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?

typeAliases:设置类型别名,即为某个具体的类型设置一个别名,在MyBatis的范围中,就可以使用别名来表示一个具体的类型

    <!--
        typeAliases:设置类型别名,即为某个具体的类型设置一个别名,在MyBatis的范围中,就可以使用别名来表示一个具体的类型
        type:设置需要起别名的类型
        alias:设置某个类型的别名 (不设置默认为最后的类名且不区分大小写)
    -->
    <typeAliases>
        <typeAlias type="com.atguigu.mybatis.pojo.User" alias="User"></typeAlias>
        <!--通过包设置别名,指定包下所有类型将全部拥有默认的别名,即类名不区分大小写-->
        <package name="com.atguigu.mybatis.pojo"/>
    </typeAliases>
9、引入多个映射文件

以包的方式引入映射文件,但是必须满足两个条件:
(1)mapper接口和映射文件所在的包必须一致
(2)mapper接口的名字和映射文件的名字必须一致
在这里插入图片描述

    <mappers>
        <package name="com.atguigu.mybatis.mapper"/>
    </mappers>

二、MyBatis获取参数值

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

  • ${}的本质就是字符串拼接,#{}的本质就是占位符赋值
  • ${}使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;但是#{}使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时, 可以自动添加单引号

1、若mapper中的方法参数为单个的字面量类型,此时可以通过#{}和 以任意的内容获取参数值,一定要注意 {}以任意的内容获取参数值,一定要注意 以任意的内容获取参数值,一定要注意{}的单引号问题。(mybatis3.5以后)

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

这里的username其实可以是任何值
2、方法参数为多个的字面量类型
此时MyBatis会自动将这些参数放在一个map集合中,以arg0,arg1…为键,以参数为值;以
param1,param2…为键,以参数为值; 因此只需要通过 ${}#{}访问map集合的键就可以获取相对应的值,注意${}需要手动加单引号

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

若mapper接口中的方法需要的参数为多个时,此时也可以手动创建map集合,将这些数据放在map中只需要通过KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#̲{}访问map集合的键就可以获…{}需要手动加单引号。

        Map<String,Object> map = new HashMap<>();
        map.put("username","wanwan");
        map.put("password","107");
        User wanwan = mapper.checkLoginByMap(map);
    <!--User checkLoginByMap(Map<String,Object> map);-->
    <select id="checkLoginByMap" resultType="User">
        select * from t_user where username =#{username} and password = #{password}
    </select>

3、Mapper接口方法参数为实体类类型的对象,此时可以使用KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#̲{},通过访问实体类对象中的属…{}需要手动加单引号。
属性名:与成员变量无关,只跟get/set方法有关,将方法名中的get/set去掉,剩余部分首字母小写即为属性名。

    <!--void insertUser(User user);-->
    <insert id="insertUser">
        insert into t_user values(null ,#{username},#{password},#{age},#{gender},#{email})
    </insert>

4、使用@Param标识参数
可以通过@Param注解标识mapper接口中的方法参数,此时,会将这些参数放在map集合中,以@Param注解的value属性值为键,以参数为值;param1,param2…为键,以参数为值;只需要通过${}和#{}访问map集合的键就可以获取相对应的值。

    <!--User checkLoginParam(@Param("username") String username, @Param("password")String password);-->
    <select id="checkLoginParam" resultType="User">
        select * from t_user where username =#{username} and password = #{password}
    </select>

建议访问实体类对象中的属性名和使用@Param

三、Mybatis的各种查询功能

一般查询

当查询的数据为多条时,不能使用实体类作为返回值,否则会抛出异常TooManyResultsException;但是若查询的数据只有一条,可以使用实体类或集合作为返回值
1、查询单个数据
在MyBatis中,对于Java中常用的类型都设置了类型别名

  • 例如: java.lang.Integer–>int|integer
  • 例如: int–>_int|_integer
  • 例如: Map–>map,List–>list
    <!--Integer getCount();-->
    <select id="getCount" resultType="int">
        select count(*) from t_user
    </select>

2、查询一条数据为map集合

    <!--Map<String,Object> getUserByIdToMap(@Param("id")Integer id);-->
    <select id="getUserByIdToMap" resultType="map">
        select * from t_user where id = #{id}
    </select>

结果为:userByIdToMap = {password=107, gender=女, id=4, age=1, email=107@qq.com, username=wanwan}
3、查询多条数据为map集合
(1)方法一:将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此时可以将这些map放在一个list集合中获取

    <!--List<Map<String,Object>> getAllUser();-->
    <select id="getAllUser" resultType="map">
        select * from t_user
    </select>
allUser = [{password=123456, gender=男, id=1, age=23, email=12345@qq.com, username=admin}, {password=107, gender=女, id=4, age=1, email=107@qq.com, username=wanwan}, {password=123456, gender=女, id=5, age=18, email=6462@qq.com, username=lxy}]

(2)方法二:将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,并且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的
map集合

    <!--@MapKey("id")-->
    <!--Map<String,Object> getAllUser();-->
    <select id="getAllUser" resultType="map">
        select * from t_user
    </select>
allUser = {1={password=123456, gender=男, id=1, age=23, email=12345@qq.com, username=admin}, 
4={password=107, gender=女, id=4, age=1, email=107@qq.com, username=wanwan}, 
5={password=123456, gender=女, id=5, age=18, email=6462@qq.com, username=lxy}}

使用#{}会出错的情况

模糊查询

%表示任意个数的任意字符,_表示单个的任意字符
直接使用'%#{mohu}%'会使得不能识别#{mohu}

    <!--List<User> getUserByLike(@Param("mohu")String mohu);-->
    <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>
批量删除

delete from t_user where id in(7,8)
${}不会自动添加单引号,#{}会出现单引号

    <!--void deleteUserByIds(@Param("ids")String ids);-->
    <delete id="deleteUserByIds">
        delete from t_user where id in(${ids})
    </delete>
动态设置表名
<!--List<User> getAllUser(@Param("tableName") String tableName);-->
<select id="getAllUser" resultType="User">
	select * from ${tableName}
</select>

添加功能获取自增的主键

useGeneratedKeys:表示当前添加功能使用自增的主键
keyProperty::因为增删改有统一的返回值是受影响的行数,将添加的数据的自增主键放在传输的参数user对象的某个属性中

    <!--void insertUser(User user);-->
    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
        insert into t_user values (null ,#{username},#{password},#{age},#{gender},#{email})
    </insert>

三、自定义映射resultMap

若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用下划线),实体类中的属性名符合Java的规则(使用驼峰),此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系

  • a>可以通过为字段起别名的方式,保证和实体类中的属性名保持一致
 	<!--Emp getEmpByEmpId(@Param("empId") Integer empId);-->
    <select id="getEmpByEmpId" resultType="Emp">
        <!--select emp_id empId,emp_name empName,age,gender from t_emp where emp_id = #{empId}-->
        select * from t_emp where emp_id = #{empId}
    </select>
  • b>可以在MyBatis的核心配置文件中设置一个全局配置信息mapUnderscoreToCamelCase,可以在查询表中数据时,自动将_类型的字段名转换为驼峰。例如:字段名user_name,设置了mapUnderscoreToCamelCase,此时字段名就会转换为userName
	<settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
	<!--Emp getEmpByEmpId(@Param("empId") Integer empId);-->
    <select id="getEmpByEmpId" resultType="Emp">
        select * from t_emp where emp_id = #{empId}
    </select>

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

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

  • id:表示自定义映射的唯一标识
  • type:查询的数据要映射的实体类的类型

子标签:

  • id:设置主键的映射关系
  • result:设置普通字段的映射关系
  • association:设置多对一的映射关系
  • collection:设置一对多的映射关系
  • 属性:
    property:设置映射关系中实体类中的属性名
    column:设置映射关系中表中的字段名
	<resultMap id="empResultMap" type="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
    </resultMap>
    <!--Emp getEmpByEmpId(@Param("empId") Integer empId);-->
    <select id="getEmpByEmpId" resultMap="empResultMap">
        select * from t_emp where emp_id = #{empId}
    </select>

多对一映射处理

1.级联方式处理映射关系

数据库查询结果中dept_id和dept_name需要映射到dept对象中。
在这里插入图片描述

	<resultMap id="empAndDeptResultMap" type="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="dept_id" property="dept.deptId"></result>
        <result column="dept_name" property="dept.deptName"></result>
    </resultMap>

    <!--Emp getEmpAndDeptByEmpId(@Param("empId") Integer empId);-->
    <select id="getEmpAndDeptByEmpId" resultMap="empAndDeptResultMap">
        SELECT t_emp.*,t_dept.dept_name FROM t_emp LEFT JOIN t_dept on t_emp.dept_id=t_dept.dept_id where emp_id = #{empId}
    </select>
2、使用association处理映射关系

association:处理多对一的映射关系(处理实体类类型的属性)

	<resultMap id="empAndDeptResultMap" type="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></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>
3、分步查询

(1)查询员工信息

	<resultMap id="empAndDeptByStepResultMap" type="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <!--
            property:设置需要处理映射关系的属性的属性名
            select:设置分步查询的sql的唯一标识
            column:设置分步查询的sql的条件
        -->
        <association property="dept"
                     select="com.atguigu.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
                     column="dept_id">
        </association>
    </resultMap>
    
    <!--Emp getEmpAndDeptByStepOne(@Param("empId") Integer empId);-->
    <select id="getEmpAndDeptByStepOne" resultMap="empAndDeptByStepResultMap">
        select * from t_emp where emp_id = #{empId}
    </select>

(2)根据员工所对应的部门id查询部门信息

    <!--Dept getEmpAndDeptByStepTwo(@Param("dept_id")Integer dept_id);-->
    <select id="getEmpAndDeptByStepTwo" resultType="Dept">
        select * from t_dept where dept_id = #{dept_id}
    </select>

分步查询的优点:可以实现延迟加载(没有获取部门的操作就不会执行查询部门的sql)
但是必须在核心配置文件中设置全局配置信息:

  • lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载
  • aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属
    性会按需加载
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>

此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql。此时可通过association和
collection中的fetchType属性设置当前的分步查询是否使用延迟加载, fetchType=“lazy(延迟加
载)|eager(立即加载)”

一对多映射处理

1、collection

collection:处理一对多的映射关系(处理集合类型的属性)
ofType:设置collection标签所处理的集合属性中存储数据的类型

    <resultMap id="DeptAndEmpByDeptResultMap" type="Dept">
        <id column="dept_id" property="deptId"></id>
        <result column="dept_name" property="deptName"></result>
		<!--
			ofType:设置collection标签所处理的集合属性中存储数据的类型
		-->
        <collection property="emps" ofType="Emp">
            <id column="emp_id" property="empId" ></id>
            <result column="emp_name" property="empName"></result>
            <result column="age" property="age"></result>
            <result column="gender" property="gender"></result>
        </collection>
    </resultMap>
    
    <!--Dept getDeptAndEmpByDeptId(@Param("dept_id")Integer dept_id);-->
    <select id="getDeptAndEmpByDeptId" resultMap="DeptAndEmpByDeptResultMap">
        SELECT * FROM t_emp LEFT JOIN t_dept ON t_dept.dept_id=t_emp.dept_id WHERE t_emp.dept_id= #{dept_id}
    </select>
2、分步查询

(1)查询部门信息

	<resultMap id="DeptAndEmpByStep" type="Dept">
        <id column="dept_id" property="deptId"></id>
        <result column="dept_name" property="deptName"></result>
        <collection property="emps" ofType="Emp" select="com.atguigu.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo" column="dept_id"></collection>
    </resultMap>

    <!--Dept getDeptAndEmpByStepOne(@Param("dept_id")Integer dept_id);-->
    <select id="getDeptAndEmpByStepOne" resultMap="DeptAndEmpByStep">
        select * from t_dept where dept_id = #{dept_id}
    </select>

(2)根据部门id查询部门中的所有员工

    <!--List<Emp> getDeptAndEmpByStepTwo(@Param("dept_id") Integer dept_id);-->
    <select id="getDeptAndEmpByStepTwo" resultType="Emp">
        select * from t_emp where dept_id = #{dept_id}
    </select>

四、动态SQL

动态SQL技术是一种根据特定条件动态拼装SQL语句的功能(例如,根据复选框中选中的条件进行查询,此时复选款被选中的个数和条件都是可以变化的,就需要进行动态拼装SQL语句)

1、动态sql–if标签

通过test属性中的表达式判断标签中的内容是否有效(是否会拼接到sql中)

	<!--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="gender!=null and gender!=''">
            and gender = #{gender}
        </if>
    </select>

如果第一个条件不满足,sql语句就会出错。(简单解决:where后面加上 1=1 恒成立表达式)

2、动态sql–where标签

功能:

  • a.若where标签中有条件成立,会自动生成where关键字
  • b.会自动将where标签中内容前多余的and去掉,但是其中内容后多余的and无法去掉
  • c.若where标签中无条件成立,则where标签没有任何功能
	<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="gender!=null and gender!=''">
                and gender = #{gender}
            </if>
        </where>
    </select>

3、动态sql–trim标签

功能:带有where的功能,还可添加其他参数

  • prefix、suffix:在sql内容前或者后面添加指定内容
  • prefixOverride、suffixOverride:在标签前面或后面去掉指定内容

4、动态sql–choose、when、otherwise标签

相当与java中的if…else if…else
when至少设置一个,otherwise最多设置一个
只要有一个when成立,就不继续判断下面的语句了

	<!--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="age!=null and age!=''">
                    and age = #{age}
                </when>
                <when test="gender!=null and gender!=''">
                    and gender = #{gender}
                </when>
            </choose>
        </where>
    </select>

5、动态sql–foreach

collection:设置要循环的数组或集合
item:用一个字符串表示数组或集合中的每个数据
seperator:设置每次循环的数据之间的分隔符
open:循环的所有内容以什么开始
close:循环的所有内容以什么结束
(1)批量添加

<!--void insertMoreEmp(@Param("emps") List<Emp> emps);-->
    <insert id="insertMoreEmp">
        insert into t_emp values
        <foreach collection="emps" item="emp" separator=",">
            (null,#{emp.empName},#{emp.age},#{emp.gender},null)
        </foreach>
    </insert>

(2)批量删除

<!--void deleteMoreEmp(@Param("empIds") Integer[] empIds);-->
    <delete id="deleteMoreEmp">
        delete from t_emp where
        <foreach collection="empIds" item="empId" separator="or">
            emp_id = #{empId}
        </foreach>
<!--         delete from t_emp where emp_id in     -->
<!--        <foreach collection="empIds" item="empId" open="(" separator="," close=")">-->
<!--            #{empId}-->
<!--        </foreach>-->
    </delete>

6、动态sql–sql

可以记录一段sql,在需要用的地方使用include标签进行引用

<sql id="empColumns">
        emp_id,emp_name,age,gender,dept_id
    </sql>
    <!--List<Emp> getEmpByCondition(Emp emp);-->
    <select id="getEmpByCondition" resultType="Emp">
        select <include refid="empColumns"></include> from t_emp
    </select>

五、MyBatis的缓存

MyBatis的一级缓存

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

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

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

MyBatis的二级缓存

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

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

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

二级缓存的相关配置

在mapper配置文件中添加的cache标签可以设置一些属性:
①eviction属性:缓存回收策略,默认的是 LRU。
LRU(Least Recently Used) – 最近最少使用的:移除最长时间不被使用的对象。
FIFO(First in First out) – 先进先出:按对象进入缓存的顺序来移除它们。
SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
②flushInterval属性:刷新间隔,单位毫秒默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新
③size属性:引用数目,正整数代表缓存最多可以存储多少个对象,太大容易导致内存溢出
④readOnly属性:只读, true/false。true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了 很重要的性能优势。
false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false。

MyBatis缓存查询的顺序

先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用。
如果二级缓存没有命中,再查询一级缓存
如果一级缓存也没有命中,则查询数据库
SqlSession关闭之后,一级缓存中的数据会写入二级缓存

逆向工程

正向工程:先创建Java实体类,由框架负责根据实体类生成数据库表。 Hibernate是支持正向工程的。
逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成如下资源:

  • Java实体类
  • Mapper接口
  • Mapper映射文件
1、 创建逆向工程的步骤

①添加依赖和插件(pom.xml)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>ssm</artifactId>
        <groupId>com.atguigu.mybatis</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>mybatis_mbg</artifactId>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <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>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</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.16</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
    </build>

</project>

②创建MyBatis的核心配置文件

③创建逆向工程的配置文件
文件名必须是: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="MyBatis3">
        <!-- 数据库的连接信息 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3305/ssm?serverTimezone=UTC"
                        userId="root"
                        password="123456">
            <property name="useInformationSchema" value="true"/>
        </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>

④执行MBG插件的generate目标
在这里插入图片描述

2、QBC查询
@Test
    public void testMBG(){
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        //根据id查询数据
        Emp emp1 = mapper.selectByPrimaryKey(1);
        System.out.println("emp = " + emp1);
        //查询所有数据
        List<Emp> emps = mapper.selectByExample(null);
        emps.forEach(System.out::println);
        //条件查询
        EmpExample empExample = new EmpExample();
//select emp_id, emp_name, age, gender, dept_id from t_emp WHERE ( emp_name = ? and age >= ? )
//        empExample.createCriteria().andEmpNameEqualTo("张三").andAgeGreaterThanOrEqualTo(20);

//select emp_id, emp_name, age, gender, dept_id from t_emp WHERE ( emp_name = ? ) or( age = ? )
        empExample.createCriteria().andEmpNameEqualTo("张三");
        empExample.or().andAgeEqualTo(20);

        //普通修改
        Emp emp = new Emp(1,"晚晚",null,"女");
//        mapper.updateByPrimaryKey(emp);
        //选择性修改  update t_emp SET emp_name = ?, gender = ? where emp_id = ?
        mapper.updateByPrimaryKeySelective(emp);
    }

updateByPrimaryKey与updateByPrimaryKeySelective区别:前者会将赋值为null和为赋值的字段一并写入数据库进行修改;后者只会改变非null值。

分页插件

limit index,pageSize

pageSize:每页显示的条数
pageNum:当前页的页码
index:当前页的起始索引,index=(pageNum-1)*pageSize
count:总记录数
totalPage:总页数
totalPage = count / pageSize;
if(count % pageSize != 0){
totalPage += 1;
}

分页插件的使用步骤

①添加依赖

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

②配置分页插件(配置到dependencies中)
在MyBatis的核心配置文件中配置插件

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

分页插件的使用

a>在查询功能之前使用PageHelper.startPage(int pageNum, int pageSize)开启分页功能

  • pageNum:当前页的页码
  • pageSize:每页显示的条数
    b>在查询获取list集合之后,使用PageInfo pageInfo = new PageInfo<>(List list, int
  • navigatePages)获取分页相关数据
  • list:分页之后的数据
  • navigatePages:导航分页的页码数
    @Test
    public void testDe(){
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        Page<Object> page = PageHelper.startPage(2, 5);
        List<Emp> emps = mapper.selectByExample(null);

        //emps.forEach(System.out::println);
        PageInfo<Emp> empPageInfo = new PageInfo<>(emps, 5);
        System.out.println("empPageInfo = " + empPageInfo);
    }

c>分页相关数据

PageInfo{
pageNum=8, pageSize=4, size=2, startRow=29, endRow=30, total=30, pages=8,
list=Page{count=true, pageNum=8, pageSize=4, startRow=28, endRow=32, total=30,
pages=8, reasonable=false, pageSizeZero=false},
prePage=7, nextPage=0, isFirstPage=false, isLastPage=true, hasPreviousPage=true,
hasNextPage=false, navigatePages=5, navigateFirstPage4, navigateLastPage8,
navigatepageNums=[4, 5, 6, 7, 8]
}
pageNum:当前页的页码
pageSize:每页显示的条数
size:当前页显示的真实条数
total:总记录数
pages:总页数
prePage:上一页的页码
nextPage:下一页的页码
isFirstPage/isLastPage:是否为第一页/最后一页
hasPreviousPage/hasNextPage:是否存在上一页/下一页
navigatePages:导航分页的页码数
navigatepageNums:导航分页的页码,[1,2,3,4,5]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值