MyBatis笔记
MyBatis
MyBatis特性
- MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架
- MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集
- MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录
- MyBatis 是一个 半自动的ORM(Object Relation Mapping)框架
下载
下载地址
持久化层技术对比
-
JDBC
- SQL 夹杂在Java代码中耦合度高
- 维护不易且实际开发需求中 SQL 有变化,频繁修改的情况多见
- 代码冗长,开发效率低
-
Hibernate 和 JPA
- 操作简便,开发效率高
- 程序中的长难复杂 SQL 需要绕过框架
- 内部自动生产的 SQL,不容易做特殊优化
- 基于全映射的全自动框架,大量字段的 POJO 进行部分映射时比较困难
- 反射操作太多,导致数据库性能下降
-
MyBatis
- 轻量级,性能出色
- SQL 和 Java 编码分开,功能边界清晰。Java代码专注业务、SQL语句专注数据
- 开发效率稍逊于HIbernate,但是完全能够接受
开发环境
idea:2019.3.5
MySQL:8.0
MyBatis:3.5.10
Maven:3.6.1
开始写代码
1.创建Maven工程
2.配置打包方式为jar
3.引入依赖
pom.xml
<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.30</version>
</dependency>
</dependencies>
4.mybatis配置文件
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>
<!--设置连接数据库的环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="xxxxxxxxx"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<mapper resource="mappers/UserMapper.xml"/>
</mappers>
</configuration>
5.创建数据库建表(略)并在Java代码中创建对应实体类
Users.java
package com.xust.mybatis.pojo;
public class Users {
private Integer id;
private String username;
private String password;
private Integer age;
private String sex;
private String email;
public Users() {
}
public Users(Integer id, String username, String password, Integer age, String sex, String email) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.sex = sex;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Users{" +
"id=" + id +
", username="" + username + """ +
", password="" + password + """ +
", age=" + age +
", sex="" + sex + """ +
", email="" + email + """ +
"}";
}
}
6.创建mapper接口(不需要实现类)
UserMapper.java
package com.xust.mybatis.mapper;
/**
* mybatis面向接口编程两个一致
* 1.映射文件的namespace要和mapper的全类名保持一致
* 2.映射文件中SQL语句的id要和mapper接口中的方法名一致
*/
public interface UserMapper {
/**
* 添加用户信息
*/
int insertUser();
}
7.创建MyBatis映射文件
映射文件的namespace要和mapper的全类名保持一致
映射文件中SQL语句的id要和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">
<mapper namespace="com.xust.mybatis.mapper.UserMapper">
<!--int insertUser();-->
<insert id="insertUser">
insert into t_user values(null,"张三","123",23,"女","123456@qq.com")
</insert>
</mapper>
8.junit测试
SqlSession:代表Java程序和数据库之间的会话。HttpSession是Java程序和浏览器之间的会话
SqlSessionFactory:是生产SqlSession的工厂
MyBatisTest.java
package com.xust.mybatis.test;
import com.xust.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 testMyBatis() throws IOException {
//加载核心配置文件
InputStream is= Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
//获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(is);
//获取SqlSession
SqlSession sqlSession=sqlSessionFactory.openSession();
//获取mapper接口对象
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
//测试功能
int result=mapper.insertUser();
//提交事务
sqlSession.commit();
System.out.println("result:"+result);
}
}
上面是手动提交事务,SqlSession默认不自动提交事务,自动提交可以在获取sqlSession对象时,使用SqlSession sqlSession = sqlSessionFactory.openSession(true),传入一个Boolean类型的参数,值为true,这样就可以自动提交。
9.加入log4j日志功能
引入依赖
<!-- log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
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)
" />
</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>
日志的级别:FATAL(致命)>ERROR(错误)>WARN(警告)>INFO(信息)>DEBUG(调试)
日志级别越低,打印越详细
增删改查
查询功能必须指定resultType或resultMap
resultType:设置默认映射(字段名和属性名一致)
resultMap:设置自定义映射(一对多,多对一,字段名和属性名不一致)
<?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.xust.mybatis.mapper.UserMapper">
<!--int insertUser();-->
<insert id="insertUser">
insert into t_user values(null,"张三","123",23,"女","123456@qq.com")
</insert>
<!--void updateUser();-->
<update id="updateUser">
update t_user set username="李四" where id=1
</update>
<!--void deleteUser();-->
<delete id="deleteUser">
delete from t_user where id=2
</delete>
<!--Users getUserById();;-->
<!--
查询功能必须指定resultType或resultMap
resultType:设置默认映射(字段名和属性名一致)
resultMap:设置自定义映射(一对多,多对一,字段名和属性名不一致)
-->
<select id="getUserById" resultType="com.xust.mybatis.pojo.Users">
select * from t_user where id=3
</select>
<!--List<Users> getAllUser();-->
<select id="getAllUser" resultType="com.xust.mybatis.pojo.Users">
select * from t_user
</select>
</mapper>
MyBatis核心配置文件
标签顺序
properties、settings、typeAliases、typeHandlers、objectFactory、objectWrapperFactory、reflectorFactory、plugins、environments、databaseIdProvider、mappers
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文件,此时就可以${属性名}的方式访问属性值-->
<properties resource="jdbc.properties"></properties>
<typeAliases>
<!--
typeAlias:设置某个具体的类型的别名
属性:
type:需要设置别名的类型的全类名
alias:设置此类型的别名,且别名不区分大小写。若不设置此属性,该类型拥有默认的别名,即类名
-->
<!--<typeAlias type="com.atguigu.mybatis.bean.User"></typeAlias>-->
<!--<typeAlias type="com.atguigu.mybatis.bean.User" alias="user">
</typeAlias>-->
<!--以包为单位,设置改包下所有的类型都拥有默认的别名,即类名且不区分大小写-->
<package name="com.xust.mybatis.bean"/>
</typeAliases>
<!--
environments:配置多个连接数据库的环境
属性:
default:设置默认使用的环境的id
-->
<environments default="development">
<!--
environment:配置某个具体的环境
id:表示连接数据库的环境的唯一标识,不能重复
-->
<environment id="development">
<!--
transactionManager:设置事务管理方式
属性:
type:设置事务管理方式,type="JDBC|MANAGED"
type="JDBC":设置当前环境的事务管理都必须手动处理
type="MANAGED":设置事务被管理,例如spring
-->
<transactionManager type="JDBC"/>
<!--
dataSource:设置数据源
属性:
type:设置数据源的类型,type="POOLED|UNPOOLED|JNDI"
type="POOLED":使用数据库连接池,即会将创建的连接进行缓存,下次使用可以从缓存中直接获取,不需要重新创建
type="UNPOOLED":不使用数据库连接池,即每次使用连接都需要重新创建
type="JNDI":调用上下文中的数据源
-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<!--
映射文件较多时
以包为单位,将包下所有的映射文件引入核心配置文件
注意:
1. 此方式必须保证mapper接口和mapper映射文件必须在相同的包下
2. mapper接口要和mapper映射文件的名字一致
3.在resources下创建和java目录下包名相同的文件夹时,用/间隔不能用.
-->
<mapper resource="mappers/UserMapper.xml"/>
</mappers>
</configuration>
jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=xxxxxxx
idea中设置核心配置文件模板
MyBatis中mapper获取参数值的两种方式
${}:字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号
{}:使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号
单个字面量类型的参数
{}中username可替换为任意值,${}要手动添加””
Test.java
public class ParameterTest {
@Test
public void testGetUserByUsername(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
ParameterMapper mapper=sqlSession.getMapper(ParameterMapper.class);
Users user=mapper.GetUserByUsername("李四");
System.out.println(user);
}
}
#{}
<select id="GetUserByUsername" resultType="users">
select * from t_user where username=#{username}
</select>
${}
<select id="GetUserByUsername" resultType="users">
select * from t_user where username="${username}"
</select>
多个字面量类型的参数
若mapper接口中的方法参数为多个时,此时MyBatis会自动将这些参数放在一个map集合中
- 以arg0,arg1…为键,以参数为值;
- 以param1,param2…为键,以参数为值;
{}中必须按照上面的参数写
Test.java
public class ParameterTest {
@Test
public void testCheckLogin(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
ParameterMapper mapper=sqlSession.getMapper(ParameterMapper.class);
Users user=mapper.checkLogin("李四","123");
System.out.println(user);
}
}
#{}
<select id="checkLogin" resultType="users">
select * from t_user where username=#{arg0} and password=#{arg1}
</select>
${}
<select id="checkLogin" resultType="User">
select * from t_user where username ="${param1}" and password ="${param2}"
</select>
map集合类型的参数
mapper接口中的方法需要的参数为多个时,此时可以手动创建map集合,将这些数据放在map中只需要通过${}和#{}访问map集合的键就可以获取相对应的值
Test.java
public class ParameterTest {
@Test
public void testCheckLoginByMap(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
ParameterMapper mapper=sqlSession.getMapper(ParameterMapper.class);
Map<String,Object> map=new HashMap<>();
map.put("username","李四");
map.put("password","123");
Users user=mapper.checkUserByMap(map);
System.out.println(user);
}
}
#{}
<select id="checkUserByMap" resultType="users">
select * from t_user where username=#{username} and password=#{password}
</select>
${}略
实体类类型的参数
通过访问实体类对象中的属性名获取属性值
Test.java
public class ParameterTest {
@Test
public void testInsertUser(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
ParameterMapper mapper=sqlSession.getMapper(ParameterMapper.class);
int result=mapper.insertUser(new Users(null,"王五","123",23,"男","123@q.com"));
System.out.println(result);
}
}
#{}
<insert id="insertUser">
insert into t_user values(null,#{username},#{password},#{age},#{sex},#{email})
</insert>
${}略
使用@Param注解命名参数
可以通过@Param注解标识mapper接口中的方法参数,此时,会将这些参数放在map集合中
- 以@Param注解的value属性值为键,以参数为值
- 以param1,param2…为键,以参数为值
Test.java
public class ParameterTest {
@Test
public void testChesckLoginByParam(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
ParameterMapper mapper=sqlSession.getMapper(ParameterMapper.class);
Users user=mapper.checkLoginByParam("李四","123");
System.out.println(user);
}
}
mapper.java
Users checkLogdinByParam(@Param("username") String username,@Param("password") String password);
mapper.xml
<select id="checkLogdinByParam" resultType="users">
select * from t_user where username=#{username} and password=#{password}
</select>
MyBatis查询功能
查询一个实体类对象
Users getUserById(@Param("id") Integer id);
<select id="getUserById" resultType="users">
select * from t_user where id=#{id}
</select>
public class SelectMapperTest {
@Test
public void getUsereById(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
SelectMapper mapper=sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getUserById(3));
}
}
查询List集合
List<Users> getAllUser();
<select id="getAllUser" resultType="users">
select * from t_user
</select>
public class SelectMapperTest {
@Test
public void getAllUsers(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
SelectMapper mapper=sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getAllUser());
}
}
查询单个数据
Integer getCount();
<select id="getCount" resultType="java.lang.Integer">
select count(*) from t_user
</select>
public class SelectMapperTest {
@Test
public void testGetCount(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
SelectMapper mapper=sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getCount());
}
}
查询一条数据为map集合
Map<String,Object> getUserByIdToMap(@Param("id") Integer id);
<select id="getUserByIdToMap" resultType="map">
select * from t_user where id=#{id}
</select>
public class SelectMapperTest {
@Test
public void testGetUserByIdToMap(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
SelectMapper mapper=sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getUserByIdToMap(3));
}
}
查询多条数据为map集合
法一:
List<Map<String,Object>> getAllUserToMap();
<select id="getAllUserToMap" resultType="map">
select * from t_user
</select>
public class SelectMapperTest {
@Test
public void testGetAllUserToMap(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
SelectMapper mapper=sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getAllUserToMap());
}
}
法二:
@MapKey("id")
Map<String,Object> getAllUserToMap1();
<select id="getAllUserToMap1" resultType="map">
select * from t_user
</select>
public class SelectMapperTest {
@Test
public void testGetAllUserToMap1(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
SelectMapper mapper=sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getAllUserToMap1());
}
}
特殊SQL的执行
模糊查询
第三种方法最常用
List<Users> getUserByLike(@Param("username") String username);
<select id="getUserByLike" resultType="users">
<!--select * from t_user where username like "%${username}%"-->
<!--select * from t_user where username like concat("%",#{username},"%")-->
select * from t_user where username like "%"#{username}"%"
</select>
public class SQLMapperTest {
@Test
public void testGetUserByLike(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
List<Users> list=mapper.getUserByLike("a");
System.out.println(list);
}
}
批量删除
int deleteMore(@Param("ids") String ids);
<delete id="deleteMore">
delete from t_user where id in (${ids})
</delete>
public class SQLMapperTest {
@Test
public void testDeleteMore(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
int result=mapper.deleteMore("1,2,3");
System.out.println(result);
}
}
动态设置表名
List<Users> getUserByTableName(@Param("tableName") String tableName);
<select id="getUserByTableName" resultType="users">
select * from ${tableName}
</select>
public class SQLMapperTest {
@Test
public void testGetUserByTableName(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
List<Users> list=mapper.getUserByTableName("t_user");
System.out.println(list);
}
}
添加功能获取自增的主键
在插入一条数据的同时就可以获得对应的id,不需要插入后再去查询对应数据的id
useGeneratedKeys:设置使用自增的主键
keyProperty:因为增删改有统一的返回值是受影响的行数,因此只能将获取的自增的主键放在传输的参数user对象的某个属性中
void insertUser(Users user);
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into t_user values(null,#{username},#{password},#{age},#{sex},#{email})
</insert>
public class SQLMapperTest {
@Test
public void testInsertUser(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
Users user=new Users(null,"赵六","123",23,"男","123@qq.com");
mapper.insertUser(user);
System.out.println(user);
}
}
自定义映射resultMap
字段名与属性名不一致
数据库
Emp.java
package com.xust.mybatis.pojo;
public class Emp {
private Integer eid;
private String empName;
private Integer age;
private String sex;
private String email;
public Emp() {
}
public Emp(Integer eid, String empName, Integer age, String sex, String email) {
this.eid = eid;
this.empName = empName;
this.age = age;
this.sex = sex;
this.email = email;
}
public Integer getEid() {
return eid;
}
public void setEid(Integer eid) {
this.eid = eid;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Emp{" +
"eid=" + eid +
", empName="" + empName + """ +
", age=" + age +
", sex="" + sex + """ +
", email="" + email + """ +
"}";
}
}
public class ResultMapTest {
@Test
public void testGetAllEmp(){
SqlSession sqlSessaion= SqlSessionUtils.getSqlSession();
EmpMapper mapper=sqlSessaion.getMapper(EmpMapper.class);
List<Emp> list=mapper.getAllEmp();
list.forEach(emp-> System.out.println(emp));
}
}
方法一:为字段起别名,使之与属性名称相同
EmpMapper.xml
<select id="getAllEmp" resultType="emp">
select eid,emp_name empNaem,age,sex,email from t_emp
</select>
方法二:配置映射
在mybatis-config.xml中添加配置后自动将下划线映射为驼峰
mybatis-config.xml
<!--设置mybatis全局配置-->
<settings>
<!--将下划线自动映射为驼峰,emp_name->empName-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
EmpMapper.xml
<select id="getAllEmp" resultType="emp">
select * from t_emp
</select>
方法三:自定义映射resultMap
所有属性都要列出来
EmpMapper.xml
<!--id用于主键,result用于普通属性-->
<resultMap id="empResultMap" type="Emp">
<!--property属性名,column字段名-->
<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>
</resultMap>
<!--getAllEmp-->
<select id="getAllEmp" resultMap="empResultMap">
select * from t_emp
</select>
多对一映射
方法一:级联操作
Emp.java
public class Emp {
private Integer eid;
private String empName;
private Integer age;
private String sex;
private String email;
private Dept dept;
......
}
Dept.java
package com.xust.mybatis.pojo;
public class Dept {
private Integer did;
private String deptName;
......
}
EmpMapper.xml
<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>
<!--getEmpAndDept-->
<select id="getAllEmp" resultMap="empAndDeptResultMapOne">
select * from t_emp left join t_dept on t_emp.did=t_dept.did where t_emp.eid=#{eid}
</select>
方法二:association
association用来处理多对一的映射关系
javaType中是类型名
EmpMapper.xml
<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>
方法三:分步查询
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>
<!--
property:多对一对应属性
select:分布查询sql的唯一标识,全类名
column:分布查询的条件
-->
<association property="dept"
select="com.xust.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
column="did"></association>
</resultMap>
<!--getEmpAndDeptByStepOne-->
<select id="getEmpAndDeptByStepOne" resultMap="empAndDeptByStepResultMap">
select * from t_emp where eid=#{eid}
</select>
DeptMapper.xml
<select id="getEmpAndDeptByStepTwo" resultType="Dept">
select * from t_dept where did=#{did}
</select>
public class ResultMapTest {
@Test
public void testGetEmpAndDeptByStep(){
SqlSession sqlSessaion= SqlSessionUtils.getSqlSession();
EmpMapper mapper=sqlSessaion.getMapper(EmpMapper.class);
Emp emp=mapper.getEmpAndDeptByStepOne(1);
System.out.println(emp);
}
}
一对多映射
Dept.java
public class Dept {
private Integer did;
private String deptName;
private List<Emp> emps;
......
}
方法一: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>
<!--getDeptAndEmp-->
<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>
public class ResultMapTest {
@Test
public void testGetDeptAndEmp(){
SqlSession sqlSessaion= SqlSessionUtils.getSqlSession();
DeptMapper mapper=sqlSessaion.getMapper(DeptMapper.class);
Dept dept=mapper.getDeptAndEmp(1);
System.out.println(dept);
}
}
方法二:分步查询
DeptMapper.xml
<resultMap id="deptAndEmpByStepResultMap" type="Dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
<collection property="emps"
select="com.xust.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
column="did"></collection>
</resultMap>
<!--getDeptAndEmpByStepOne-->
<select id="getDeptAndEmpByStepOne" resultMap="deptAndEmpByStepResultMap">
select * from t_dept where did=#{did}
</select>
EmpMapper.xml
<select id="getDeptAndEmpByStepTwo" resultType="Emp">
select * from t_emp where did=#{did}
</select>
public class ResultMapTest {
@Test
public void testGetDeptAndEmpByStep(){
SqlSession sqlSessaion= SqlSessionUtils.getSqlSession();
DeptMapper mapper=sqlSessaion.getMapper(DeptMapper.class);
Dept dept=mapper.getDeptAndEmpByStepOne(1);
System.out.println(dept);
}
}
动态SQL
Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决拼接SQL语句字符串时的痛点问题
if标签
if标签可以对test中接收到的属性值进行判断,为true则拼接if标签下的内容
where后加1=1为了更好实现拼接效果,防止出现拼接错误
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>
public class DynamicSQLMapperTest {
@Test
public void testGetEmpByCondition(){
SqlSession sqlSessaion= SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper=sqlSessaion.getMapper(DynamicSQLMapper.class);
List<Emp> list=mapper.getEmpByCondition(new Emp(null,"张三",12,"男","123@qq.com"));
System.out.println(list);
}
}
where标签
相比直接使用if标签,where标签会自动清除多余的and和or,条件全不满足时where不起作用,不会出现拼接错误
但是where标签只能将内容之前多余的and和or清除,如果and和or放在拼接的语句之后,则不能清除
<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>
trim标签
prefix/suffix:将trim标签中内容前面/后面添加指定内容
prefixOverrides/suffixOverrides:将trim标签中内容前面/后面去掉指定内容
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<trim prefix="where" suffixOverrides="and|or">
<if test="empName != null and empName !=""">
emp_name = #{empName} and
</if>
<if test="age != null and age !=""">
age = #{age} and
</if>
<if test="sex != null and sex !=""">
sex = #{sex} or
</if>
<if test="email != null and email !=""">
email = #{email}
</if>
</trim>
</select>
choose,when,otherwise标签
相当于if…else if…else,只会执行一个
when至少要有一个,otherwise至多只有一个
<select id="getEmpByChoose" resultType="Emp">
select * from t_emp
<where>
<choose>
<when test="empName!=null and empName!=""">
emp_name=#{empName}
</when>
<when test="age!=null and age!=""">
age=#{age}
</when>
<when test="sex!=null and sex!=""">
sex=#{sex}
</when>
<when test="email!=null and email!=""">
email=#{email}
</when>
<otherwise>
did=1
</otherwise>
</choose>
</where>
</select>
foreach标签
collection:设置要循环的数组或集合
item:表示集合或数组中的每一个数据
separator:设置循环体之间的分隔符,分隔符前后默认有一个空格
open:开始符
close:结束符
int deleteMoreByArray(@Param("eids") Integer[] eids);
<delete id="deleteMoreByArray">
delete from t_emp where eid in
<foreach collection="eids" item="eid" separator="," open="(" close=")">
#{eid}
</foreach>
</delete>
public class DynamicSQLMapperTest {
@Test
public void testDeleteMoreByArray(){
SqlSession sqlSessaion= SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper=sqlSessaion.getMapper(DynamicSQLMapper.class);
int result=mapper.deleteMoreByArray(new Integer[]{6,7,8});
System.out.println(result);
}
}
批量删除
,换成or
<delete id="deleteMoreByArray">
delete from t_emp where eid in
<foreach collection="eids" item="eid" separator="or" open="(" close=")">
#{eid}
</foreach>
</delete>
批量添加
int insertMoreByList(@Param("emps") List<Emp> emps);
<insert id="insertMoreByList">
insert into t_emp values
<foreach collection="emps" item="emp" separator=",">
(null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.email},null)
</foreach>
</insert>
public class DynamicSQLMapperTest {
@Test
public void insertMoreByList() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
Emp emp1 = new Emp(null,"a",1,"男","123@qq.com");
Emp emp2 = new Emp(null,"b",1,"男","123@321.com");
Emp emp3 = new Emp(null,"c",1,"男","123@321.com");
List<Emp> emps = Arrays.asList(emp1, emp2, emp3);
mapper.insertMoreByList(emps);
System.out.println(emps);
}
}
SQL标签
sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入
<sql id="empColumns">eid,emp_name,age,sex,email</sql>
<select id="getEmpByCondition" resultType="Emp">
select <include refid="empColumns"></include> from t_emp
</select>
MyBatis缓存
MyBatis一级缓存
一级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取,不会从数据库重新访问
使一级缓存失效的四种情况:
- 不同的SqlSession对应不同的一级缓存
- 同一个SqlSession但是查询条件不同
- 同一个SqlSession两次查询期间执行了任何一次增删改操作
- 同一个SqlSession两次查询期间手动清空了缓存
MyBatis二级缓存
二级缓存是SqlSessionFactory级别,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取
二级缓存开启的条件:
- 在核心配置文件中,设置全局配置属性cacheEnabled=“true”,默认为true,不需要设置
- 在xml映射文件中设置标签
- 二级缓存必须在SqlSession关闭或提交之后有效
- 查询的数据所转换的实体类类型必须实现序列化的接口
- 使二级缓存失效的情况:两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效
二级缓存相关配置
在mapper配置文件中添加的cache标签可以设置一些属性:
eviction属性:缓存回收策略
- LRU(Least Recently Used) – 最近最少使用的:移除最长时间不被使用的对象。
- FIFO(First in First out) – 先进先出:按对象进入缓存的顺序来移除它们。
- SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
- WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
- 默认的是 LRU
flushInterval属性:刷新间隔,单位毫秒
- 默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句(增删改)时刷新
size属性:引用数目,正整数
- 代表缓存最多可以存储多少个对象,太大容易导致内存溢出
readOnly属性:只读,true/false
- true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。
- false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false
MyBatis缓存查询顺序
先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用
如果二级缓存没有命中,再查询一级缓存
如果一级缓存也没有命中,则查询数据库
SqlSession关闭之后,一级缓存中的数据会写入二级缓存
整合第三方缓存
向pom.xml中添加依赖
<!-- 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>
resources下创建ehcache.xml文件
<?xml version="1.0" encoding="utf-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<!-- 磁盘保存路径 -->
<diskStore path="D:atguiguehcache"/>
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
设置二级缓存类型
mapper.xml的cache标签中
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
加入logback日志
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<!-- 指定日志输出的位置 -->
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- 日志输出的格式 -->
<!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体内容、换行 -->
<pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern>
</encoder>
</appender>
<!-- 设置全局日志级别。日志级别按顺序分别是:DEBUG、INFO、WARN、ERROR -->
<!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
<root level="DEBUG">
<!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
<appender-ref ref="STDOUT" />
</root>
<!-- 根据特殊需求指定局部日志级别 -->
<logger name="com.atguigu.crowd.mapper" level="DEBUG"/>
</configuration>
MyBatis逆向工程
正向工程:先创建Java实体类,由框架负责根据实体类生成数据库表。Hibernate是支持正向工程的。
逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成Java实体类,Mapper接口,Mapper映射文件。
创建逆向工程的步骤
1.添加依赖和插件
pom.xml
<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.30</version>
</dependency>
<!-- log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</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>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.2</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
2.创建MyBatis核心配置文件
Mybatis.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"/>
<typeAliases>
<package name=""/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name=""/>
</mappers>
</configuration>
3.将log4j.xml和jdbc.properties复制过来
4.创建逆向工程配置文件
文件名必须是generatorConfig.xml
MyBatis3Simple: 生成基本的CRUD
MyBatis3: 生成带条件的CRUD(使用最多)
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/mybatis"
userId="root"
password="xpx24167830">
</jdbcConnection>
<!-- javaBean的生成策略-->
<javaModelGenerator targetPackage="com.xust.mybatis.pojo" targetProject=".srcmainjava">
<!--是否能够使用子包-->
<property name="enableSubPackages" value="true" />
<!--去掉字符串前后空格-->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- SQL映射文件的生成策略 -->
<sqlMapGenerator targetPackage="com.xust.mybatis.mapper"
targetProject=".srcmainesources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- Mapper接口的生成策略 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.xust.mybatis.mapper" targetProject=".srcmainjava">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 逆向分析的表 -->
<!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
<!-- domainObjectName属性指定生成出来的实体类的类名 -->
<table tableName="t_emp" domainObjectName="Emp"/>
<table tableName="t_dept" domainObjectName="Dept"/>
</context>
</generatorConfiguration>
5.执行MBG插件的generate目标
双击mybatis-generator:generate
6.通过Example进行查询演示
public class MBGTest {
@Test
public void testMBG(){
try {
InputStream is= Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession=sqlSessionFactory.openSession(true);
EmpMapper mapper=sqlSession.getMapper(EmpMapper.class);
//查询所有
// List<Emp> list=mapper.selectByExample(null);
// list.forEach(emp-> System.out.println(emp));
//条件查询
EmpExample example=new EmpExample();
example.createCriteria().andEmpNameEqualTo("张三").andAgeGreaterThanOrEqualTo(11);
List<Emp> list=mapper.selectByExample(example);
list.forEach(emp-> System.out.println(emp));
} catch (IOException e) {
e.printStackTrace();
}
}
}
分页插件
步骤
添加依赖
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
配置插件
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
开启分页功能
public class PageHelperTest {
@Test
public void testPageHelper(){
try {
InputStream is= Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession=sqlSessionFactory.openSession(true);
EmpMapper mapper=sqlSession.getMapper(EmpMapper.class);
PageHelper.startPage(1,4);
List<Emp> list = mapper.selectByExample(null);
list.forEach(emp-> System.out.println(emp));
} catch (IOException e) {
e.printStackTrace();
}
}
}