MyBatis技术
目录
写在前面
为什么要学习MyBatis技术?MyBatis框架是干什么的?首先需要了解一下ORM,即Object Relation Mapping->对象关系映射。这里的对象指的是java对象,关系指的是数据库中的关系模型。而对象关系映射,也就是ORM,指的就是在Java对象和数据库的关系模型之间建立一种对应关系,比如用一个Java的Student类,去对应数据库中的一张student表,Java类中的属性和数据表中的列一一对应。Student类就对应student表,一个Student对象就对应student表中的一行数据。
那么来说说我们的MyBatis,这是一种半自动的ORM持久层(Dao层)框架。
为什么是半自动?因为用MyBatis框架进行开发的时候,需要我们来手动编写sql语句。而全自动的ORM框架,例如hibernate,则不需要我们手动编写sql语句。由于Mybatis是半自动的,所有它有较高的灵活性,可以根据需要,自由地对SQL进行定制。
也因为要手写SQL,当要切换数据库时,SQL语句可能就要重写,因为不同的数据库有不同的方言(Dialect),所以mybatis的数据库无关性低。
虽然mybatis需要手写SQL,但相比JDBC,它提供了输入映射和输出映射,可以很方便地进行SQL参数设置,以及结果集封装。并且还提供了关联查询和动态SQL等功能,极大地提升了开发的效率。并且它的学习成本也比hibernate低很多。
一、MyBatis快速入门
1.1新建一个Maven模块
1.2在pom文件中导入jar包
需要导入的jar包如下
<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.11</version>
<scope>test</scope>
</dependency>
<!--Mysql驱动jar包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- log4j2 日志门面 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.1</version>
</dependency>
<!-- log4j2 日志实面 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.1</version>
</dependency>
<!-- junit 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
1.3创建核心配置文件
核心配置文件(mybatis-config.xml)内容如下,有关核心配置文件内容中各个标签的说明以后再提
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties"></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>
<mapper resource=""/>
</mappers>
</configuration>
1.4创建mapper接口
1.5创建映射文件
在创建映射文件的时候,我们将映射文件放在resources文件下。并且模块名要和UserMapper接口所在的包名一致,由于我们现在创建的是Directory,所以文件之间要用/分割开。
并且映射文件的名字要和Mapper接口的类名一致
UserMapper.xml映射文件的内容如下
<?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">
<!--namespace中的内容要和Mapper接口的全类名一致-->
<mapper namespace="com.zyb.mybatis.mapper.UserMapper">
</mapper>
1.6创建实体类
实体类内容---->其实就相当于对应数据库表的一个JavaBean而已
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private String gender;
private String email;
public User(Integer id, String username, String password, Integer age, String gender, String email) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.gender = gender;
this.email = email;
}
public User() {
}
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
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 +
", gender='" + gender + '\'' +
", email='" + email + '\'' +
'}';
}
}
1.7创建Utilis工具类
该工具类的主要目的是为了获取SqlSession对象
ublic class SqlSessionUtil {
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
try {
//1、获取核心配置文件的输入流
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//2、获取SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//3、获取SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//4、获取sqlSession会话对象
sqlSession = sqlSessionFactory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
}
1.8在映射文件中编写Sql
1.9编写测试类
@Test
public void testUpdate(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
//获取mapper接口的代理实现类对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用mapper接口中的方法
mapper.updateUser();
sqlSession.close();
}
这样我们就实现了我们的第一个MyBatis程序了!
二、有关配置文件中标签的说明
三、MyBatis获取参数
3.1MyBatis获取参数值的两种方式
获取参数值的两种方式分别是:${}和#{}
${}的本质是字符串拼接,#{}的本质就是占位符赋值
${}使用字符串拼接的方式拼接sql,若为字符串类型或者是日期类型的字段进行赋值时,需要手动添加单引号;但是#{}使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号。
3.2单个字面量类型的参数
如果mapper接口中的方法的参数为单个的字面量类型,此时可以通过#{}或${}以任意的内容来获取参数值
由于${}的本质是字符串拼接,所以在赋值使用的时候一定要加单引号
3.3多个字面量类型的参数(1)
多个字面量类型的参数的意思就是,在Mapper接口中,参数有多个,如下
我们可以看到这个方法是通过用户名和密码的匹配来获取用户信息,那么我们如何在xml映射文件中调配呢?
然后在Test测试方法中我们就可以进行测试操作了
那么为什么必须用arg0,arg1或者param1,param2这种方式来命名呢?
这是因为mapper接口中的参数会被MyBatis以map集合的形式存储起来,
例如:以arg0,arg1…等为key,以参数为value
因此我们只需要通过#{}或者${}访问map集合的键,就可以获取相对应的值
3.4多个字面量类型的参数(2)
在(1)方案中,我们在xml映射文件中通过#{}方式引入参数的时候,只能被动的使用arg0,arg1…这样由MyBatis提供的默认值参数,
那么我们能否自定义参数名呢?
我们可以通过将mapper接口中的方法的参数改为一个map集合的形式来自定义参数类型
然后在测试类中创建map集合
这样在最后xml映射文件中的参数名就可以改为map集合中定义的key值了
3.5多个字面量类型的参数(3)
前两个说的都不是实体类对象类型的参数,那么如果我们的mapper接口中的参数是一个实体类的对象呢?
例如:
那么此时我们的xml映射文件中的配置只需要满足3.2中的情况即可,即任意赋值
测试方法如下
四、MyBatis的各种查询功能
4.1查询实体类对象
首先我们需要在Mapper接口中写书我们的查询接口
然后到xml映射文件中配置sql信息
最后编写单元测试类
4.2查询一个list集合
Mapper接口中的接口方法
/**
* 查询所有的用户信息
* @return
*/
List<User>getAllUser();
配置xml映射文件
<select id="getAllUser" resultType="User">
select * from t_user
</select>
编写单元测试类方法
@Test
public void testGetAllUser(){
SqlSession sqSession = SqSessionUtils.getSqSession();
SelectMapper mapper = sqSession.getMapper(SelectMapper.class);
List<User> allUser = mapper.getAllUser();
allUser.forEach(System.out::println);
}
当查询的数据为多条时,不能使用实体类作为返回值,否则会抛出异常TooManyResultException;但是如果查询的数据只有一条,我们可以使用实体类或者集合作为返回值
4.3查询单行单列结果
Mapper接口中的方法
/**
* 查询用户的总数量
* @return
*/
Integer getCount();
xml映射文件配置
说明:我们查询的单行单列结果的类型可能为int、String、Integer等等
Mybatis中为Java常用的类型都设置了别名,我们可以直接进行使用
Integer: int,Integer
int: int,integer
Map:map
String:string
<select id="getCount" resultType="Integer">
select count(*) from t_user
</select>
编写测试方法
@Test
public void testGetCount(){
SqlSession sqSession = SqSessionUtils.getSqSession();
SelectMapper mapper = sqSession.getMapper(SelectMapper.class);
Integer count = mapper.getCount();
System.out.println(count);
sqSession.close();
}
4.4查询结果设置为map集合
mapper接口中的方法
/**
*
* @param id
* @return
*/
Map<String,Object> getUserByIdToMap(@Param("id") Integer id);
xml映射文件
<select id="getUserByIdToMap" resultType="map">
select * from t_user where id = #{id}
</select>
测试类
@Test
public void testGetUserByIdToMap(){
SqlSession sqSession = SqSessionUtils.getSqSession();
SelectMapper mapper = sqSession.getMapper(SelectMapper.class);
Map<String, Object> map = mapper.getUserByIdToMap(1);
System.out.println(map);
sqSession.close();
}
如果当前字段的值为null,那么该字段是不会被放入map集合中的
4.5处理多行数据的map集合
方法一:将map集合再放入list集合中
mapper接口
List<Map<String,Object>> toGetAllUser();
xml映射文件
<select id="toGetAllUser" resultType="map">
select * from t_user
</select>
测试类
@Test
public void testToGetAllUser(){
SqlSession sqSession = SqSessionUtils.getSqSession();
SelectMapper mapper = sqSession.getMapper(SelectMapper.class);
List<Map<String, Object>> mapList = mapper.toGetAllUser();
System.out.println(mapList);
}
方法二:使用大map注解
mapper接口
/**
* 查询所有的用户信息为map集合
* 若查询的数据有多条,并且我们想要将数据转换为map集合的时候
* 此时有两种解决方案:
* 1、将mapper接口方法的返回值设置为泛型是map的list集合
* List<Map<String,Object>> getAllUserToMap();
* 2、将每条数据转换的map集合放在一个大的map中,但是必须要通过@MapKey注解
* MapKey注解中的参数为:将要查询的某个字段的值作为大的map的key
* @MapKey("id")
* Map<String, Object> toGetAllUser();
* @return
*/
@MapKey("id")
Map<String,Object> toGetAllUser();
xml映射文件
<select id="toGetAllUser" resultType="map">
select * from t_user
</select>
测试类
@Test
public void testToGetAllUser(){
SqlSession sqSession = SqSessionUtils.getSqSession();
SelectMapper mapper = sqSession.getMapper(SelectMapper.class);
Map<String, Object> map = mapper.toGetAllUser();
System.out.println(map);
}
五、特殊Sql的执行
5.1模糊查询
什么是模糊查询?
例如:
select * from t_user where username like '%a%';
说明:#{}占位符的方式无法对模糊查询进行赋值操作
例如我们的mapper接口:
List<User> getUserByLike(@Param("mohu")String mohu);
在xml中我们的语句是这样的:
<select id="getUserByLike" resultType="User">
select * from t_user where username like '%#{mohu}%'
</select>
我们可以回忆一下在xml映射文件中用#{}方式进行赋值的原理,是因为们mybatis把#{}当成占位符来处理了,那么这里mybatis依旧把#{}当成占位符处理,就变成了这样:‘%?%’ 很明显我们在测试方法中时无法对字符串中的?进行赋值的,所以我们应该试着采取其他的办法。
解决方法一:
既然用占位符赋值的方式不行,那么我们是否可以考虑一下采用字符串拼接的方式呢?反正模糊查询后面本来就就是一个字符串,那么我直接用${}的方式就OK了!
mapper接口
List<User> getUserByLike(@Param("mohu")String mohu);
xml映射文件
<select id="getUserByLike" resultType="User">
select * from t_user where username like '%${mohu}%'
</select>
测试类
@Test
public void testGetUserByLike(){
SqlSession sqSession = SqSessionUtils.getSqSession();
SpecialSQLMapper mapper = sqSession.getMapper(SpecialSQLMapper.class);
List<User> user = mapper.getUserByLike("a");
System.out.println(user);
}
解决方法二:
既然是因为占位符被夹在了字符串中,那么我们其实可以利用mysql中的concat关键字进行拼接操作
<select id="getUserByLike" resultType="User">
select * from t_user where username like concat('%',#{mohu},'%')
</select>
解决方法三:
方法三比较粗暴。。如下
<select id="getUserByLike" resultType="User">
select * from t_user where username like "%"#{mohu}"%"
</select>
5.2批量删除
首先说明一下在Mysql中我们是如何进行批量删除的
delete from t_user where id in(1,2,3,...);
那么在MyBatis中我们如何处理批量删除操作呢?
先展示错误的方法:用#{}的方式进行占位符赋值
<delete id="deleteMoreUser">
delete from t_user where id in(#{ids})
</delete>
测试类方法
@Test
public void testDeleteMoreUser(){
SqlSession sqSession = SqSessionUtils.getSqSession();
SpecialSQLMapper mapper = sqSession.getMapper(SpecialSQLMapper.class);
mapper.deleteMoreUser("9,10");
}
在运行之后我们发现这样会报错,那么为什么会报错呢?
这是因为#{}的本质是占位符赋值,也就是说它会为我们当前赋的值两边默认加上单引号,所以我们的sql在被解析之后变成了in (‘9,10’),很明显这样是不对的,那么我们如何进行操作?
暂时的解决方案:使用${}的方式
<delete id="deleteMoreUser">
delete from t_user where id in(${ids})
</delete>
5.3动态设置表名
什么叫动态设置表名?
其实就是类似于select * from ___这种表名未定的sql语句,那么我们应该如何为这种sql语句动态设置表名呢?
mapper接口
/**
* 处理动态设置表名
* @param tableName
* @return
*/
List<User> getUserList(@Param("tableName") String tableName);
xml映射文件
<select id="getUserList" resultType="User">
select * from #{tableName}
</select>
测试类
@Test
public void testGetUserList(){
SqlSession sqSession = SqSessionUtils.getSqSession();
SpecialSQLMapper mapper = sqSession.getMapper(SpecialSQLMapper.class);
List<User> userList = mapper.getUserList("t_user");
userList.forEach(System.out::println);
}
很明显如果我们用这样的方式会报错,为什么呢?其实还是因为#{}在本质是一种占位符赋值的方式,从而给未待定的表名加上了默认的单引号,导致查找出错。
如何解决:使用${}
xml文件配置内容如下:
<select id="getUserList" resultType="User">
select * from ${tableName}
</select>
5.4添加功能获取自增的主键
mapper接口
/**
* 测试在MyBatis中设置和获取自增的主键
*/
void insertUser(User user);
xml映射文件
<!--
userGeneratedKeys:表示当前添加功能使用自增的主键
keyProperty:将添加的数据的自增主键为实体类类型的参数的属性赋值
-->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into t_user values(null,#{username},#{password},#{age},#{gender},#{email})
</insert>
测试类
@Test
public void testInsertUser(){
SqlSession sqSession = SqSessionUtils.getSqSession();
SpecialSQLMapper mapper = sqSession.getMapper(SpecialSQLMapper.class);
User user = new User(null, "xiaoming", "123456", 23, "男", "123@qq.com");
mapper.insertUser(user);
System.out.println(user);
}
六、自定义映射resultMap
6.1使用全局配置处理字段和属性的映射关系
引入:让我们来想一下,如果我们在mysql中设置字段名的时候使用了下换线,比如emp_id,emp_name,而我们在Java的pojo类中使用的是驼峰命名法,这样如何获取到mysql中的字段属性呢?
解决方法一:为查询的字段设置别名,和属性名保持一致
mapper接口
/**
* 根据id查询员工信息
* @param empId
* @return
*/
Emp getEmpByEmpId(@Param("empId")Integer empId);
xml映射文件
<select id="getEmpByEmpId" resultType="Emp">
select emp_id as empId,emp_name as empName,age,gender from t_emp where emp_id = #{empId}
</select>
测试类
@Test
public void testGetEmpByEmpId(){
SqlSession sqSession = SqSessionUtils.getSqSession();
EmpMapper mapper = sqSession.getMapper(EmpMapper.class);
Emp emp = mapper.getEmpByEmpId(1);
System.out.println(emp);
}
解决方法二:在核心配置文件中设置一个全局配置,可以自动将下划线映射为驼峰
config核心配置文件
<!--
将下划线映射为驼峰
-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
xml映射文件
<select id="getEmpByEmpId" resultType="Emp">
select * from t_emp where emp_id = #{empId}
</select>
6.2resultMap处理字段和属性的映射关系
承接6.1,使用resultMap处理字段和属性的映射关系是第三种解决方法,具体实施如下
在之前我们在xml的select标签中一直使用的都是resultType属性,现在我们使用resultMap属性
<select id="getEmpByEmpId" resultMap="empResultMap">
select * from t_emp where emp_id = #{empId}
</select>
使用这个属性的前提是需要设置resultMap标签中的一些属性和字标签
id:唯一标识,用于和select标签中的resultMap属性产生对应关系
type:将要进行处理和字段映射关系的实体类的类型
常用子标签:
id:处理主键类型的字段和实体类中属性的映射关系
result:处理普通字段和实体类中属性的映射关系
colum:设置映射关系中的字段名,要求必须是sql查询出的某个字段
property:设置映射关系中的属性的属性名,要求必须是当前处理的实体类类型中的属性名
<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>
6.3多对一映射处理
场景模拟:
查询员工信息以及员工对应的部门信息
mapper接口中的方法
/**
* 获取员工以及所对应的部门信息
* @param empId
* @return
*/
Emp getEmpAndDeptByEmpId(@Param("empId")Integer empId);
很明显这个方法要进行外连接查询,因为我们要查找的是两张表,所以情况有些特殊。
那么如何进行多对一(多个员工可能对应一个部门)的映射处理呢?
sql核心语句:
select t_emp.*,t_dept.*
from t_emp
left join t_dept #左外连接
on t_emp.dept_id = t_dept.dept_id #on关键字紧跟连接条件
where t_emp.emp_id = #{empId}
6.3.1级联方式处理映射关系
xml映射文件内容
这里我们使用resultMap的方式进行查询,因为我们的问题处在Emp类中的Dept属性无法与当前的查询建立连接
那么我们使用result标签中的colum属性和property属性对Emp类中的Dept属性进行相关处理
注意这里的Dept是一个类属性,所以我们应该处理的是Dept类中的deptId和deptName,也就是说我们要进行调用
<resultMap id="empAndDeptResultMap" 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>
<result column="dept_id" property="dept.deptId"></result>
<result column="dept_name" property="dept.deptName"></result>
</resultMap>
<select id="getEmpAndDeptByEmpId" resultMap="empAndDeptResultMap">
select t_emp.*,t_dept.*
from t_emp
left join t_dept
on t_emp.dept_id = t_dept.dept_id
where t_emp.emp_id = #{empId}
</select>
6.3.2使用association处理映射关系
xml映射文件配置
在这里说明一下,association:处理多对一的映射关系(处理实体类类型的属性)
property:设置需要处理映射关系的属性的属性名
javaType:设置需要处理的属性的类型
<resultMap id="empAndDeptResultMap" 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>
<!--
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="empAndDeptResultMap">
select t_emp.*,t_dept.*
from t_emp
left join t_dept
on t_emp.dept_id = t_dept.dept_id
where t_emp.emp_id = #{empId}
</select>
6.3.3分步查询
分步查询的意思就是将我们要”查询员工以及该员工所对应的部门信息“的任务分成两步。
第一步是先通过EmpMapper接口以及其所对应的xml文件查询到emp中的所有属性
第二步是通过查询到的dept_id属性,作为DeptMapper接口中的参数进行第二次查找
我们需要通过配置resultMap标签让这两步联系起来
第一步:
mapper接口
/**
* 通过分步查询,查询员工以及所对应的部门信息的第一步
* @param empId
* @return
*/
Emp getEmpAndDeptByStepOne(@Param("empId")Integer empId);
xml映射文件
<resultMap id="empAndDeptByStepResultMap" 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>
<!--
property:设置需要处理映射关系的属性的属性名
select:设置分步查询的sql的唯一标识
column:将查询出的某个字段,作为分步查询的sql条件
-->
<association property="dept"
select="zyb.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
column="dept_id"></association>
</resultMap>
<select id="getEmpAndDeptByStepOne" resultMap="empAndDeptByStepResultMap">
select * from t_emp where emp_id = #{empId}
</select>
第二步:
mapper接口
/**
* 通过分步查询查询员工以及所对应的部门的第二步
* @param deptId
* @return
*/
Dept getEmpAndDeptByStepTwo(@Param("deptId")Integer deptId);
xml映射文件
<select id="getEmpAndDeptByStepTwo" resultType="Dept">
select * from t_dept where dept_id = #{deptId}
</select>
测试类
@Test
public void testGetEmpAndDeptByStep(){
SqlSession sqSession = SqSessionUtils.getSqSession();
EmpMapper mapper = sqSession.getMapper(EmpMapper.class);
Emp emp = mapper.getEmpAndDeptByStepOne(1);
System.out.println(emp);
}
6.3.4使用分步查询的好处
可以进行延迟加载
什么是延迟加载?
延迟加载就是我可以选择想要输出打印的查询结果,如果没有必要查询所有信息,也就是说没有必要查询第二张表,那么我们可以不用让mybatis帮我们查询第二张表,节约时间和内存。
例如:
在config核心配置文件中设置setting属性
<settings>
<!--
将下划线映射为驼峰
-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--
开启延迟加载
-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--
按需加载,默认为false 如果为true的话则不管是否开启延迟加载,都将加载第二个dept查询语句
-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
修改测试类的输出内容为员工的姓名
@Test
public void testGetEmpAndDeptByStep(){
SqlSession sqSession = SqSessionUtils.getSqSession();
EmpMapper mapper = sqSession.getMapper(EmpMapper.class);
Emp emp = mapper.getEmpAndDeptByStepOne(1);
System.out.println(emp.getEmpName());
}
运行程序,查看运行日志
我们可以发现只查询了Emp接口中的sql语句,而没有再单独的去查询Dept中的sql语句。
6.4一对多映射处理
一对多其实就是部门->员工
任务:根据deptId查询部门信息,并且根据部门信息将该部门所有的员工信息查找出来
6.4.1collection处理
mapper接口
/**
* 查询部门以及部门中的员工信息
* @param deptId
* @return
*/
Dept getDeptAndEmpByDeptId(@Param("deptId")Integer deptId);
xml映射文件
在这里我们依然用的是左外连接查询,也就是将两张表联立起来
其中我们的resultMap中用到了collection标签,collection标签的作用就是用来处理属性中含有List或者Map集合的元素
我们在collection标签中设置property属性为emps,对应的是我们的实体类中集合的属性名,
ofType属性对应的是实体类中List集合存储的数据的具体类型
<resultMap id="deptAndEmpResultMap" type="Dept">
<id column="dept_id" property="deptId"></id>
<result column="dept_name" property="deptName"></result>
<!--
collection标签处理一对多关系(属性中含有集合)
property属性:要处理的实体类中的具体属性名
ofType:集合的类型
-->
<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>
<select id="getDeptAndEmpByDeptId" resultMap="deptAndEmpResultMap">
select *
from t_dept
left join t_emp
on t_dept.dept_id = t_emp.emp_id
where t_dept.dept_id=#{deptId}
</select>
测试类
@Test
public void testGetDeptAndEmpByDeptId(){
SqlSession sqSession = SqSessionUtils.getSqSession();
DeptMapper mapper = sqSession.getMapper(DeptMapper.class);
Dept dept = mapper.getDeptAndEmpByDeptId(1);
System.out.println(dept);
}
6.4.2分步查询
分步查询的步骤是:先根据deptId查找Dpet表,然后根据查找到的dept_id字段,作为参数值,在Emp表中进行查找
Dept接口
/**
* 通过分步查询查询部门以及部门中的员工信息的第一步
* @param deptId
* @return
*/
Dept getDeptAndEmpByStepOne(@Param("deptId") Integer deptId);
Dept的xml映射文件
<resultMap id="deptAndEmpResultMapByStep" type="Dept">
<id column="dept_id" property="deptId"></id>
<result column="dept_name" property="deptName"></result>
<collection property="emps"
select="zyb.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwp"
column="dept_id"></collection>
</resultMap>
<select id="getDeptAndEmpByStepOne" resultMap="deptAndEmpResultMapByStep">
select * from t_dept where dept_id = #{deptId}
</select>
Emp接口
/**
* 通过分步查询 查询部门以及部门中的员工信息 的第二步
* @param deptId
* @return
*/
List<Emp> getDeptAndEmpByStepTwo(@Param("deptId") Integer deptId);
Emp的xml映射文件
<select id="getDeptAndEmpByStepTwp" resultType="Emp">
select * from t_emp where dept_id = #{deptId}
</select>
七、动态Sql
MyBatis框架的动态Sql技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决拼接Sql语句字符串时的问题
7.1if标签
if标签可以通过test属性的表达式进行判断,如果表达式的结果为true,则标签中的内容会执行;反之标签中的内容则不会执行
使用:
创建一个Mapper接口方法 根据条件查询员工信息
/**
*根据条件查询员工信息
* @return
*/
List<Emp> getEmpByCondition(Emp emp);
xml映射文件
在这里我们通过使用where后面加上if标签的方式,实现动态SQL查询。
<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>
7.2where标签
功能一:如果where标签中有if条件成立,那么mybatis会自动为我们生成where关键字,筛选条件为满足if的那个条件
功能二:会自动将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="age!=null and age!=''">
and age = #{age}
</if>
<if test="gender!=null and gender!=''">
and gender = #{gender}
</if>
</where>
</select>
7.3trim标签
属性 prefix、suffix:在标签中内容前面或后面添加指定内容
prefixOverrides、suffixOverrides:在标签的前边或后边去掉指定内容
xml语法
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<trim prefix="where" suffixOverrides="and" >
<if test="empName!=null and empName!=''">
emp_name = #{empName} and
</if>
<if test="age!=null and age!=''">
age = #{age} and
</if>
<if test="gender!=null and gender!=''">
gender = #{gender}
</if>
</trim>
</select>
7.4choose、when、otherwise标签
这几个标签组合起来就相当于if…else if…else这样的语句
其中when至少要设置一个,otherwise最多只能设置一个
when之间是并列的关系,即if elseif这样 执行一个when之后,下边的when就都不会再执行了
<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="gender!=null and gender!=''">
gender = #{gender}
</when>
</choose>
</where>
</select>
7.5foreach标签
7.5.1批量添加
foreach标签的作用在于通过循环的方式进行批量添加或者删除操作
批量添加操作接口
/**
* 实现对数据内容的批量添加
* @param emps
*/
void insertMoreEmp(@Param("emps") List<Emp> emps);
xml映射文件
如果我们不使用foreach标签进行循环添加的话,我们之前是如何实现批量添加呢?
insert into t_temp values (...),(...),(...)....
很明显,这种一个括号一个括号的方式太过于低级
那么我们在这里只需要循环括号就可以了
使用foreach标签,其中collection属性对应我们要添加的集合的属性名,
item属性用一个字符串表示数组或集合中的每一个元素
括号之间和括号之间应该用逗号隔开,所以我们用separator属性,设置每一个循环的间隔符,即逗号
<insert id="insertMoreEmp">
insert into t_emp values
<foreach collection="emps" item="emp" separator=",">
(null,#{emp.empName},#{emp.age},#{emp.gender},null)
</foreach>
</insert>
测试类
@Test
public void testInsertMoreEmp(){
SqlSession sqSession = SqlSessionUtils.getSqSession();
DynamicSQLMapper mapper = sqSession.getMapper(DynamicSQLMapper.class);
Emp emp1 = new Emp(null, "小明1", 20, "男");
Emp emp2 = new Emp(null, "小明2", 20, "男");
Emp emp3 = new Emp(null, "小明3", 20, "男");
List<Emp> list = Arrays.asList(emp1,emp2,emp3);
mapper.insertMoreEmp(list);
}
7.5.2批量删除
批量删除操作和批量添加操作其实有一种异曲同工之妙,都是通过foreach标签进行循环操作执行
在批量添加操作中我们使用List集合进行演示,那么现在我们用数组进行示范
/**
* 实现对数据内容的批量删除
* @param empIds
*/
void deleteMoreEmp(@Param("empIds") Integer[] empIds);
xml映射文件
方法一:通过模糊查询的in关键字进行删除操作
<delete id="deleteMoreEmp"> delete from t_emp where emp_id in ( <foreach collection="empIds" item="empId" separator=","> #{empId} </foreach> )- </delete>
方法二:通过where条件筛选+or关键字进行删除
<delete id="deleteMoreEmp">
delete from t_temp where
<foreach collection="empIds" item="empId" separator="or">
emp_id = #{empId}
</foreach>
</delete>
@Test
public void testDeleteMoreEmp(){
SqlSession sqSession = SqlSessionUtils.getSqSession();
DynamicSQLMapper mapper = sqSession.getMapper(DynamicSQLMapper.class);
Integer[] empIds = new Integer[]{6,7};
mapper.deleteMoreEmp(empIds);
}
7.6sql标签
sql标签可以记录一段sql代码,在以后需要用的地方使用include标签进行引用
使用实例
八、MyBatis的缓存
8.1Mybatis的一级缓存
一级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据时,就会从缓存中直接获取,不会从数据库重新访问
直观的看到MyBatis缓存:我们可以用两个变量来分别查询一次相同的sql语句
可以看出我们第二次的emp2变量查询的结果是从第一次查询的结果而来的,顾名思义为SqlSession的缓存
使一级缓存失效的四种情况:
1、不同的SqlSession对应不同的一级缓存
2、同一个SqlSession但是查询条件不同
查询条件不同,这都不是一个sql,咋读取缓存。。
3、同一个SqlSession两次查询期间执行了任何一次增删改操作
这个没什么好说的,因为任意一次增删改都会导致数据库本身的数据发生变化,所以清空缓存是必然的。不然第二次查询有什么用呢?数据都改变了。
4、同一个SqlSession两次查询期间手动清空了缓存
sqlSession.celarCache();
8.2Mybatis的二级缓存
二级缓存是SqlSessionFactory级别的,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取
二级缓存开启的条件:
①在核心配置文件中,设置全局配置属性cacheEnabled=“true”(默认为true,不需要设置)
②在映射文件中设置标签
③二级缓存必须在SqlSession关闭或提交之后有效
④查询的数据所转换的实体类类型必须实现序列化的接口
二级缓存失效的条件:
在两次查询之间执行任意的增删改操作,会使一级和二级缓存同时失效
8.3二级缓存的相关配置
在mapper配置文件中添加的cache标签可以设置一些属性:
①eviction属性:缓存回收策略,默认的是LRU
LRU(Least Recently Used)—最近最少使用的:移除最长时间不被使用的对象。
FIFO(First in First out)—先进先出:按对象进入缓存的顺序来移除它们。
SOFT—软引用:移除基于垃圾回收器状态和软引用规则的对象。
WEAK—弱引用:更积极的移除基于垃圾收集器状态和弱引用规则的对象。
②flushInterval属性:刷新间隔,单位为毫秒
默认情况是不设置刷新间隔,缓存仅仅调用语句时刷新
③size属性:引用数目,正整数
代表缓存最多可以存储多少个对象,太大容易导致内存溢出
④readOnly属性:只读,true/false
true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。
false:读写缓存;会返回缓存对象的拷贝(通过序列化)。
8.4Mybatis缓存查询的顺序
先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用。
如果二级缓存没有命中,再查询一级缓存。
如果一级缓存也没有命中,则查询数据库。
SqlSession关闭之后,一级缓存中的数据会写入缓存。
九、MyBatis的逆向工程
正向工程:先创建Java实体类,由框架负责根据实体类生成数据库表。Hibernate支持正向工程
逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成如下资源
Java实体类
Mapper接口
Mapper映射文件
9.1创建逆向工程的步骤
①添加依赖和插件
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!--Mysql驱动jar包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!--log4j2 日志门面-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.1</version>
</dependency>
<!-- log4j2 日志实面 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.1</version>
</dependency>
<!-- junit 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</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>
9.2创建MyBatis核心配置文件
这个没什么好说的,和之前的一样就ok
9.3创建逆向工程的配置文件
该配置文件的名字必须是generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--
targetRuntime:执行生成的逆向工程的版本
MyBatis3Simple:生成基本的CRUD(清新简洁版)
MyBatis3:生成带条件的CRUD(奢华尊享版)
-->
<context id="DB2Tables" targetRuntime="MyBatis3Simple">
<!--数据库连接参数 -->
<jdbcConnection
driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"
userId="root"
password="020826">
</jdbcConnection>
<!--JavaBean生成策略-->
<javaModelGenerator targetPackage="com.zyb.mybatis.pojo" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--Sql映射文件的生成策略-->
<sqlMapGenerator targetPackage="com.zyb.mybatis.mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- Mappp接口生成策略 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.zyb.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>
9.4执行MBG插件的generate目标
十、分页插件
limit、index、pageSize
index:当前页的起始索引,index = (pageNum-1)*pageSize
pageSize:每页显示的条数
pageNum:当前页的页码
例如 pageSize=4,pageNum=1,则index=0,limit0,4
pageSize=4,pageNum=3,则index=8(当前页的起始索引其实就是前面几页的数据之和,也就是第…条数据),limit8,4
10.1分页插件的使用步骤
①添加依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
<dependency>
②配置分页插件(在config.xml的核心配置文件中设置)
<plugins>
<plugin interceptor = "com.github.pagehelper.PageInterceptor">
</plugins>