特性
1. MyBatis是支持定制化SQL,存储过程以及高级映射的优秀的持久层框架
2. MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集
3. MyBatis可以使用简单XML或注解用于配置和原始映射,将接口和java的POJO(普通的JAVA对象)映射成数据库中的记录
4. MyBatis是一个半自动的ORM框架。
流程
创建mapper接口
MyBatis中的mapper接口相当于以前的dao。但是区别在于,mapper仅仅是接口,我们不需要提供实现类
package com.atguigu.mybatis.mapper;
public interface UserMapper {
/**
* 添加用户信息
*/
int insertUser();
}
创建MyBatis的映射文件
相关概念:ORM(Object Relationship Mapping)对象关系映射。
对象:Java的实体类对象
关系:关系型数据库
映射:二者之间的对应关系
Java概念 | 数据库概念 |
---|---|
类 | 表 |
属性 | 字段/列 |
对象 | 记录/行 |
1. 映射文件的命名规则
表所对应的实体类的类名+Mapper.xml
- 例如:表t_user,映射的实体类为User,所对应的映射文件为UserMapper.xml
- 因此一个映射文件对应一个实体类,对应一张表的操作
- MyBatis映射文件用于编写SQL,访问以及操作表中的数据
- MyBatis映射文件存放的位置是src/main/resources/mappers目录下
2. MyBatis中可以面向接口操作数据,要保证两个一致
- mapper接口的全类名和映射文件的命名空间(namespace)保持一致
- mapper接口中方法的方法名和映射文件中编写SQL的标签的id属性保持一致
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.mapper.UserMapper">
<!--int insertUser();-->
<insert id="insertUser">
insert into t_user values(1,'张三','123',23,'男','123456@qq.com')
</insert>
</mapper>
通过junit测试功能
- SqlSession:代表Java程序和数据库之间的会话。(HttpSession是Java程序和浏览器之间的会话)
- SqlSessionFactory:是“生产”SqlSession的“工厂”
- 工厂模式:如果创建某一个对象,使用的过程基本固定,那么我们就可以把创建这个对象的相关代码封装到一个“工厂类”中,以后都使用这个工厂类来“生产”我们需要的对象
public class UserMapperTest {
@Test
public void testInsertUser() throws IOException {
//读取MyBatis的核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory,生产SqlSession对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//获取sqlSession,此时通过SqlSession对象所操作的sql都必须手动提交或回滚事务
//SqlSession sqlSession = sqlSessionFactory.openSession();
//创建SqlSession对象,此时通过SqlSession对象所操作的sql都会自动提交
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//通过代理模式创建UserMapper接口的代理实现类对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//调用UserMapper接口中的方法,就可以根据UserMapper的全类名匹配元素文件,通过调用的方法名匹配映射文件中的SQL标签,并执行标签中的SQL语句
int result = userMapper.insertUser();
//提交事务
//sqlSession.commit();
System.out.println("result:" + result);
}
}
此时需要手动提交事务,如果要自动提交事务,则在获取sqlSession对象时,使用SqlSession sqlSession = sqlSessionFactory.openSession(true);,传入一个Boolean类型的参数,值为true,这样就可以自动提交
MyBatis的增删改查
-
添加
<!--int insertUser();--> <insert id="insertUser"> insert into t_user values(null,'admin','123456',23,'男','12345@qq.com') </insert>
-
删除
<!--int deleteUser();--> <delete id="deleteUser"> delete from t_user where id = 6 </delete>
-
修改
<!--int updateUser();--> <update id="updateUser"> update t_user set username = '张三' where id = 5 </update>
-
查询一个实体类对象
<!--User getUserById();--> <select id="getUserById" resultType="com.atguigu.mybatis.bean.User"> select * from t_user where id = 2 </select>
-
查询集合
<!--List<User> getUserList();--> <select id="getUserList" resultType="com.atguigu.mybatis.bean.User"> select * from t_user </select>
注意 1. 查询的标签select必须设置属性resultType或resultMap,用于设置实体类和数据库表的映射关系 - resultType:自动映射,用于属性名和表中字段名一致的情况 - resultMap:自定义映射,用于一对多或多对一或字段名和属性名不一致的情况 2. 当查询的数据为多条时,不能使用实体类作为返回值,只能使用集合,否则会抛出异常TooManyResultsException;但是若查询的 数据只有一条,可以使用实体类或集合作为返回值
MyBatis获取参数值的两种方式
在idea中设置配置文件的模板
1. 在settings中的Editor中的File and Code Templates
2. +进行创建并且写入内容
JDBC获取参数值
@Test
public void testJDBC throws Exeption{
String username="admin";
Class.forName(""); //驱动名称
Connection connection DriverManager.getConnection("","","")//分别为url,user,password
PreparedStatement ps=connection.prepareStatement("select * from t_user where username=?"); //?占位符赋值
ps.setString(1,username); //给第一个参数设置值
}
MyBatis
获取参数的方式
1. ${}本质字符串拼接
2. #{}本质占位符赋值
MyBatis获取参数值的各种情况
1. mapper接口方法的参数为单个的字面量类型
可以通过${}和#{}以任意的名称获取参数值,在{}中可以随便写,主要是获取值。但是需要注意${}的单引号问题。
a. 接口中定义方法
/**
* 根据用户名来获取用户信息
*/
User getUserByUsername(String username);
b. 在映射文件中写sql语句
<select id="getUserByUsername" resultType="User">
select * from t_user where username= #{username}
或者
select * from t_user where username= '${username}'
</select>
2. mapper接口方法的参数为多个时
mybatis以arg0,arg1...为键,以参数为值。以param1,param2..为键,以参数为值
a. 接口中定义方法
/**
* 验证登陆
*/
User checkLogin(String username, String password);
b. 在映射文件中写sql语句
<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 * from t_user where username= #{arg0} and password = #{param2}
或者
'${}'和上面的类似
</select>
3. 若mapper接口的方法的参数有多个时,可以手动将这些参数放在一个map中存储
以键的方式访问值
a. 接口中定义方法
/**
* 验证登陆
*/
User checkLogin(Map<String,Object> map);
b. 在映射文件中写sql语句
<select id="checkLogin" resultType="User">
select * from t_user where username= #{username} and password = #{password}
其他的和第二种情况类似
</select>
4. mapper接口方法的参数是一个实体类类型的参数
通过属性的方式访问属性值
a. 接口中定义方法
/**
* 添加用用户
*/
int insertUser(User user);
b. 在映射文件中写sql语句
<select id="insertUser">
insert into t_user values(null,#{username},#{password},#{age},#{sex}.#{email})
</select>
5. 使用@Param注解命名参数
以@Param注解的值为键,以参数为值。以param1,param2...为键,以参数为值
a. 接口中定义方法
/**
* 验证登陆
*/
User checkLoginByParam(@Param(value='username') String username,@Param(value='password') String password);
b. 在映射文件中写sql语句
<select id="checkLogin" resultType="User">
select * from t_user where username= #{username} and password = #{password}
其他的和第二种情况类似
</select>
MyBatis各种查询功能
1. 若查询出来的数据只有一条,可以通过实体类对象或者list集合或者map集合接收
/**
* 根据id查询用户信息
*/
User getUserById(@Param(value = "id") Integer id);
2. 若查询出来的数据有多条
a. 可以通过实体类型的List集合来接收,一定不能通过实体类对象接收,此时会抛出异常。
/**
* 查询所有的用户信息
*/
List<User> getAllUser();
b. 可以通过map类型的的list集合来接收
/**
* 查询多个用户信息为map集合
*/
List<Map<String, Object>> getAllUserToMap();
c. 可以通过注解@MapKey(唯一字段),此时就可以将每条数据转换的map集合作为值,以某个字段的值作为键,放在同一个map集合中。
/**
* 查询多个用户信息为map集合
*/
@MapKey("id")
Map<String, Object> getAllUserToMap();
特殊SQL的执行
模糊查询
1. 模糊查询中不能直接使用#{}来进行参数获取,可以使用${}来进行参数获取。
<select id="getUserByLike" resultType="User">
select * from t_user where username like '%${username}%'
</select>
2. 可以使用concat结合#{username}
<select id="getUserByLike" resultType="User">
select * from t_user where username like concat('%',#{username},'%')
</select>
3. 可以使用"%"结合#{username}
<select id="getUserByLike" resultType="User">
select * from t_user where username like "%"#{username}"%"
</select>
批量删除
不能使用#{},使用${}
<select id="delete">
delete from t_user where id in (${ids})
</select>
动态设置表名
不能使用#{},使用${}。表名不能加单引号。
获取添加功能自增的主键
/**
* 增加用户信息
*/
void insert(User user);
1. userGeneratedKeys:设置了当前标签中的sql使用了自增的主键
2. keyProperty:将自增的主键的值赋给传输到映射文件中参数的某个属性
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into t_user values(null,#{username},#{password},#{age},#{sex},#{email})
</insert>
测试程序
User user = new User(null,"王五","123",30,"男","123@163.com");
mapper.insert(user);
Integer id = user.getId();
System.out.println(id);
输出 3 //自增的主键
自定义映射resultMap
若字段名和实体类中的属性名不一致,则可以通过resultMap设置自定义映射,即使字段名和属性名一致的属性也要映射,也就是全部属性都要列出来。可以通过以下三种方式来进行映射:
1. resultMap: 设置自定义映射
<resultMap id="empResultMap" type="Emp"> id:表示自定义映射的唯一标识,不能重复
type:查询的数据要映射的实体类的类型
<id property="eid" column="eid"></id> id:设置主键的映射关系
<result property="empName" column="emp_name"></result> result: 设置普通字段的映射关系
<result property="age" column="age"></result> property:设置映射关系中实体类中的属性名
<result property="sex" column="sex"></result> column: 设置映射关系中表中的字段名
<result property="email" column="email"></result>
</resultMap>
<!--List<Emp> getAllEmp();-->
<select id="getAllEmp" resultMap="empResultMap">
select * from t_emp
</select>
2. 可以通过为字段起别名的方式,保证和实体类中的属性名保持一致
<!--List<Emp> getAllEmp();-->
<select id="getAllEmp" resultType="Emp">
select eid,emp_name empName,age,sex,email from t_emp
</select>
3. 可以在MyBatis的核心配置文件中的`setting`标签中,设置一个全局配置信息mapUnderscoreToCamelCase,可以在查询表中数据时,自 动将_类型的字段名转换为驼峰,例如:字段名user_name,设置了mapUnderscoreToCamelCase,此时字段名就会转换为userName。[核心 配置文件详解](#核心配置文件详解)
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
多对一的映射
实现方法
功能
查询员工信息以及员工所对应部门的信息
1. 定义实体类对象
public class Emp {
private Integer eid;
private String empName;
private Integer age;
private String sex;
private String email;
private Dept dept;
//...构造器、get、set方法等
}
public class Dept {
private Integer did;
private String deptName;
//...构造器、get、set方法等
}
2. Mapper接口的映射文件,我们可以通过三种方式实现多对一
a.级联方式
<resultMap id="empAndDeptResultMapOne" type="Emp">
<id property="eid" column="eid"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<result property="email" column="email"></result>
<result property="dept.did" column="did"></result>
<result property="dept.deptName" column="dept_name"></result>
</resultMap>
b. 使用association处理映射关系
- association:处理多对一的映射关系
- property:需要处理多对的映射关系的属性名
- javaType:该属性的类型
<resultMap id="empAndDeptResultMapTwo" type="Emp">
<id property="eid" column="eid"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<result property="email" column="email"></result>
<association property="dept" javaType="Dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
</association>
</resultMap>
c. 分步查询
EmpMapper.xml
<resultMap id="empAndDeptByStepResultMap" type="Emp">
<id property="eid" column="eid"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<result property="email" column="email"></result>
<association property="dept"
select="com.atguigu.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
column="did"></association>
</resultMap>
<!--Emp getEmpAndDeptByStepOne(@Param("eid") Integer eid);-->
<select id="getEmpAndDeptByStepOne" resultMap="empAndDeptByStepResultMap">
select * from t_emp where eid = #{eid}
</select>
DeptMapper.xml
<!--此处的resultMap仅是处理字段和属性的映射关系-->
<resultMap id="EmpAndDeptByStepTwoResultMap" type="Dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
</resultMap>
<!--Dept getEmpAndDeptByStepTwo(@Param("did") Integer did);-->
<select id="getEmpAndDeptByStepTwo" resultMap="EmpAndDeptByStepTwoResultMap">
select * from t_dept where did = #{did}
</select>
延迟加载
分步查询的优点:可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息:
- lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载
- aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。 否则,每个属性会按需加载
- 此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql。此时可通过association和collection中的fetchType属性设置当 前的分步查询是否使用延迟加载,fetchType="lazy(延迟加载)|eager(立即加载)".
一对多的映射
创建Dept对象
public class Dept {
private Integer did;
private String deptName;
private List<Emp> emps;
//...构造器、get、set方法等
}
1. collection
collection:处理一对多的映射关系的标签
ofType:表示该属性所对应的集合中存储数据的类型
<resultMap id="DeptAndEmpResultMap" type="Dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
<collection property="emps" ofType="Emp">
<id property="eid" column="eid"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<result property="email" column="email"></result>
</collection>
</resultMap>
<!--Dept getDeptAndEmp(@Param("did") Integer did);-->
<select id="getDeptAndEmp" resultMap="DeptAndEmpResultMap">
select * from t_dept left join t_emp on t_dept.did = t_emp.did where t_dept.did = #{did}
</select>
2. 分步查询
a. 第一步:查询部门信息
Dept getDeptAndEmpByStepOne(@Param("did") Integer did);
<resultMap id="DeptAndEmpByStepOneResultMap" type="Dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
<collection property="emps"
select="com.atguigu.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
column="did"></collection>
</resultMap>
<!--Dept getDeptAndEmpByStepOne(@Param("did") Integer did);-->
<select id="getDeptAndEmpByStepOne" resultMap="DeptAndEmpByStepOneResultMap">
select * from t_dept where did = #{did}
</select>
b. 第二步:根据did查询员工的信息
List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);
<select id="getDeptAndEmpByStepTwo" resultType="Emp">
select * from t_emp where did = #{did}
</select>
动态SQL
MyBatis框架的动态SQL技术是一种根据特定条件动态拼接SQL语句的功能,它存在的意义是为了解决拼接SQL语句字符串时的痛点问题。
if
根据标签中test属性所对应的表达式决定标签中的内容是否需要拼接到SQL中
1. if标签可通过test属性(即传递过来的数据)的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会 执行
2. 在where后面添加一个恒成立条件`1=1`。这个恒成立条件并不会影响查询的结果
这个`1=1`可以用来拼接`and`语句,例如:当empName为null时
如果不加上恒成立条件,则SQL语句为`select * from t_emp where and age = ? and sex = ? and email = ?`,此时`where`会与 `and`连用,SQL语句会报错如果加上一个恒成立条件,则SQL语句为`select * from t_emp where 1= 1 and age = ? and sex = ? and email = ?`,此时不报错
<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp where 1=1
<if test="empName != null and empName !=''">
and emp_name = #{empName}
</if>
<if test="age != null and age !=''">
and age = #{age}
</if>
<if test="sex != null and sex !=''">
and sex = #{sex}
</if>
<if test="email != null and email !=''">
and email = #{email}
</if>
</select>
Where
1. 当where标签中有内容时,会自动生成where关键字,并且将内容前多余and或or去掉
2. 当where标签中没有内容时,不会生成where关键字
3. 注意:where标签不能将内容后多余的and或or自动去掉
4. where和if一般结合使用:
<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<where>
<if test="empName != null and empName !=''">
emp_name = #{empName}
</if>
<if test="age != null and age !=''">
and age = #{age}
</if>
<if test="sex != null and sex !=''">
and sex = #{sex}
</if>
<if test="email != null and email !=''">
and email = #{email}
</if>
</where>
</select>
MyBatis的缓存
一级缓存
一级缓存时SqlSession级别的,通过同一SqlSession查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取,不会从数据库重新访问。
使一级缓存失效的四种情况:
1. 不同的SqlSession对应不同的一级缓存
2. 同一个SqlSession但是查询条件不同
3. 同一个SqlSession两次查询期间执行了任何一次增删改操作
4. 同一个SqlSession两次查询期间手动清空了缓存
二级缓存
1. 二级缓存是SqlSessionFactory级别,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被缓存;此后若再次执行相同的查 询语句,结果就会从缓存获取。
2. 二级缓存开启的条件:
1. 在核心配置文件中,设置全局配置属性cacheEnabled="true",默认为true,不需要设置
2. 在映射文件中设置标签<cache/>
3. 二级缓存必须在SqlSession关闭或提交之后有效
4. 查询的数据所转换的实体类类型必须实现序列化接口
3. 使二级缓存失效的情况:
两次查询之间执行了任意的增删改查,会使一级和二级缓存同时失效
4. 可以添加第三方缓存来替代二级缓存,但是一级缓存不能替代。
5. 相关配置
在mapper配置文件中添加的cache标签可以设置一些属性
- eviction属性:缓存回收策略
- LRU(Least Recently Used) – 最近最少使用的:移除最长时间不被使用的对象。默认使用。
缓存查询的顺序
1. 先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用
2. 如果二级缓存没有命中,再查询一级缓存
3. 如果一级缓存也没有命中,则查询数据库
4. SqlSession关闭之后,一级缓存中的数据会写入二级缓存
MyBatis逆向工程
1. 正向工程:先创建Java实体类,由框架负责根据实体类生成数据库表。Hibernate是支持正向工程的
2. 逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成如下资源:
3. Java实体类
- Mapper接口
- Mapper映射文件
4. QBC
a. 查询
- `selectByExample`:按条件查询,需要传入一个example对象或者null;如果传入一个null,则表示没有条件,也就是查询所有数据
- `example.createCriteria().xxx`:创建条件对象,通过andXXX方法为SQL添加查询添加,每个条件之间是and关系
- `example.or().xxx`:将之前添加的条件通过or拼接其他条件
EmpExample example = new EmpExample();
//名字为张三,且年龄大于等于20
example.createCriteria().andEmpNameEqualTo("张三").andAgeGreaterThanOrEqualTo(20);
//或者did不为空
example.or().andDidIsNotNull();
List<Emp> emps = mapper.selectByExample(example);
b. 增改
- `updateByPrimaryKey`:通过主键进行数据修改,如果某一个值为null,也会将对应的字段改为null
`mapper.updateByPrimaryKey(new Emp(1,"admin",22,null,"456@qq.com",3));`
- `updateByPrimaryKeySelective()`:通过主键进行选择性数据修改,如果某个值为null,则不修改这个字段
`mapper.updateByPrimaryKeySelective(new Emp(2,"admin2",22,null,"456@qq.com",3));`