Mybatis入门 前言 什么是MyBatis?
在上面我们提到了两个词:一个是持久层,另一个是框架。
1. 快速入门 需求:使用Mybatis查询所有用户数据。
1.1 入门程序分析 Mybatis操作数据库的步骤:
准备工作(创建springboot工程、数据库表user、实体类User)
引入Mybatis的相关依赖,配置Mybatis(数据库连接信息)
编写SQL语句(注解/XML)
1.2 入门程序实现 1.2.1 准备工作 创建springboot工程,并导入 mybatis的起步依赖、mysql的驱动包。
项目工程创建完成后,自动在pom.xml文件中,导入Mybatis依赖和MySQL驱动依赖
1.2.2 配置Mybatis 在之前使用图形化客户端工具,连接MySQL数据库时,需要配置:
连接数据库的四大参数:
在springboot项目中,可以编写application.properties文件,配置数据库连接信息。我们要连接数据库,就需要配置数据库连接的基本信息,包括:driver-class-name、url 、username,password。
application.properties:
1 2 3 4 5 6 7 8 spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver spring.datasource.url =jdbc:mysql://localhost:3306/mybatis spring.datasource.username =root spring.datasource.password =1234
1.2.3 编写SQL语句 在创建出来的springboot工程中,在引导类所在包下,在创建一个包 mapper。在mapper包下创建一个接口 UserMapper ,这是一个持久层接口(Mybatis的持久层接口规范一般都叫 XxxMapper)。
@Mapper注解:表示是mybatis中的Mapper接口
程序运行时:框架会自动生成接口的实现类对象(代理对象),并给交Spring的IOC容器管理
@Select注解:代表的就是select查询,用于书写select查询语句
1.2.4 单元测试 在创建出来的SpringBoot工程中,在src下的test目录下,已经自动帮我们创建好了测试类 ,并且在测试类上已经添加了注解 @SpringBootTest,代表该测试类已经与SpringBoot整合。
该测试类在运行时,会自动通过引导类加载Spring的环境(IOC容器)。我们要测试那个bean对象,就可以直接通过@Autowired注解直接将其注入进行,然后就可以测试了。
1.3 解决SQL警告与提示 默认我们在UserMapper接口上加的@Select注解中编写SQL语句是没有提示的。 如果想让idea给我们提示对应的SQL语句,我们需要在IDEA中配置与MySQL数据库的链接。
右击SQL语句,选择ShowContextAction
产生原因:Idea和数据库没有建立连接,不识别表信息
解决方案:在Idea中配置MySQL数据库连接
在配置的时候指定连接那个数据库
2. JDBC介绍(了解) 2.1 介绍
Mybatis框架,就是对原始的JDBC程序的封装。
JDBC: ( Java DataBase Connectivity ),就是使用Java语言操作关系型数据库的一套API。
本质:
sun公司官方定义的一套操作所有关系型数据库的规范,即接口。
各个数据库厂商去实现这套接口,提供数据库驱动jar包。
我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类。
2.2 代码 下面我们看看原始的JDBC程序是如何操作数据库的。操作步骤如下:
注册驱动
获取连接对象
执行SQL语句,返回执行结果
处理执行结果
释放资源
在pom.xml文件中已引入MySQL驱动依赖,我们直接编写JDBC代码即可
JDBC具体代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 import com.plume.pojo.User;import org.junit.jupiter.api.Test;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import java.util.ArrayList;import java.util.List;public class JdbcTest { @Test public void testJdbc () throws Exception { Class.forName("com.mysql.cj.jdbc.Driver" ); String url="jdbc:mysql://127.0.0.1:3306/mybatis" ; String username = "root" ; String password = "1234" ; Connection connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); String sql="select id,name,age,gender,phone from user" ; ResultSet rs = statement.executeQuery(sql); List<User> userList = new ArrayList <>(); while (rs.next()){ int id = rs.getInt("id" ); String name = rs.getString("name" ); short age = rs.getShort("age" ); short gender = rs.getShort("gender" ); String phone = rs.getString("phone" ); User user = new User (id,name,age,gender,phone); userList.add(user); } statement.close(); connection.close(); rs.close(); for (User user : userList) { System.out.println(user); } } }
DriverManager(类):数据库驱动管理类。
作用:
注册驱动
创建java代码和数据库之间的连接,即获取Connection对象
Connection(接口):建立数据库连接的对象
Statement(接口): 数据库操作对象(执行SQL语句的对象)。
ResultSet(接口):结果集对象(一张虚拟表)
作用:sql查询语句的执行结果会封装在ResultSet中
通过上述代码,我们看到直接基于JDBC程序来操作数据库,代码实现非常繁琐,所以在项目开发中,我们很少使用。 在项目开发中,通常会使用Mybatis这类的高级技术来操作数据库,从而简化数据库操作、提高开发效率。
2.3 问题分析 原始的JDBC程序,存在以下几点问题:
数据库链接的四要素(驱动、链接、用户名、密码)全部硬编码在java代码中
查询结果的解析及封装非常繁琐
每一次查询数据库都需要获取连接,操作完毕后释放连接, 资源浪费, 性能降低
2.4 技术对比 分析了JDBC的缺点之后,我们再来看一下在mybatis中,是如何解决这些问题的:
数据库连接四要素(驱动、链接、用户名、密码),都配置在springboot默认的配置文件 application.properties中
查询结果的解析及封装,由mybatis自动完成映射封装,我们无需关注
在mybatis中使用了数据库连接池技术,从而避免了频繁的创建连接、销毁连接而带来的资源浪费。
使用SpringBoot+Mybatis的方式操作数据库,能够提升开发效率、降低资源浪费
而对于Mybatis来说,我们在开发持久层程序操作数据库时,需要重点关注以下两个方面:
application.properties
1 2 3 4 5 6 7 8 spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver spring.datasource.url =jdbc:mysql://localhost:3306/mybatis spring.datasource.username =root spring.datasource.password =1234
Mapper接口(编写SQL语句)
1 2 3 4 5 @Mapper public interface UserMapper { @Select("select id, name, age, gender, phone from user") public List<User> list () ; }
3. 数据库连接池 在前面我们所讲解的mybatis中,使用了数据库连接池技术,避免频繁的创建连接、销毁连接而带来的资源浪费。
下面我们就具体的了解下数据库连接池。
3.1 介绍 没有使用数据库连接池:
客户端执行SQL语句:要先创建一个新的连接对象,然后执行SQL语句,SQL语句执行后又需要关闭连接对象从而释放资源,每次执行SQL时都需要创建连接、销毁链接,这种频繁的重复创建销毁的过程是比较耗费计算机的性能。
数据库连接池是个容器,负责分配、管理数据库连接(Connection)
程序在启动时,会在数据库连接池(容器)中,创建一定数量的Connection对象,允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个
客户端在执行SQL时,先从连接池中获取一个Connection对象,然后在执行SQL语句,SQL语句执行完之后,释放Connection时就会把Connection对象归还给连接池(Connection对象可以复用),释放空闲时间超过最大空闲时间的连接,来避免因为没有释放连接而引起的数据库连接遗漏
客户端获取到Connection对象了,但是Connection对象并没有去访问数据库(处于空闲),数据库连接池发现Connection对象的空闲时间 > 连接池中预设的最大空闲时间,此时数据库连接池就会自动释放掉这个连接对象
数据库连接池的好处:
资源重用
提升系统响应速度
避免数据库连接遗漏
3.2 产品 要怎么样实现数据库连接池呢?
官方(sun)提供了数据库连接池标准(javax.sql.DataSource接口)
功能:获取连接
1 public Connection getConnection () throws SQLException;
第三方组织必须按照DataSource接口实现
常见的数据库连接池:
C3P0
DBCP
Druid
Hikari (springboot默认)
现在使用更多的是:Hikari、Druid (性能更优越)
Hikari(追光者) [默认的连接池]
Druid(德鲁伊)
如果我们想把默认的数据库连接池切换为Druid数据库连接池,只需要完成以下两步操作即可:
参考官方地址:https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
在pom.xml文件中引入依赖
1 2 3 4 5 6 <dependency > <groupId > com.alibaba</groupId > <artifactId > druid-spring-boot-starter</artifactId > <version > 1.2.8</version > </dependency >
在application.properties中引入数据库连接配置
方式1:
1 2 3 4 spring.datasource.druid.driver-class-name =com.mysql.cj.jdbc.Driver spring.datasource.druid.url =jdbc:mysql://localhost:3306/mybatis spring.datasource.druid.username =root spring.datasource.druid.password =123456
方式2:
1 2 3 4 spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver spring.datasource.url =jdbc:mysql://localhost:3306/mybatis spring.datasource.username =root spring.datasource.password =123456
4. lombok 4.1 介绍 Lombok是一个实用的Java类库,可以通过简单的注解来简化和消除一些必须有但显得很臃肿的Java代码。
通过注解的形式自动生成构造器、getter/setter、equals、hashcode、toString等方法,并可以自动化生成日志变量,简化java开发、提高效率。
注解
作用
@Getter/@Setter
为所有的属性提供get/set方法
@ToString
会给类自动生成易阅读的 toString 方法
@EqualsAndHashCode
根据类所拥有的非静态字段自动重写 equals 方法和 hashCode 方法
@Data
提供了更综合的生成代码功能(@Getter + @Setter + @ToString + @EqualsAndHashCode)
@NoArgsConstructor
为实体类生成无参的构造器方法
@AllArgsConstructor
为实体类生成除了static修饰的字段之外带有各参数的构造器方法。
4.2 使用 第1步:在pom.xml文件中引入依赖
1 2 3 4 5 <dependency > <groupId > org.projectlombok</groupId > <artifactId > lombok</artifactId > </dependency >
第2步:在实体类上添加注解
1 2 3 4 5 6 7 8 9 10 import lombok.Data;@Data public class User { private Integer id; private String name; private Short age; private Short gender; private String phone; }
在实体类上添加了@Data注解,那么这个类在编译时期,就会生成getter/setter、equals、hashcode、toString等方法。
说明:@Data注解中不包含全参构造方法,通常在实体类上,还会添加上:全参构造、无参构造
1 2 3 4 5 6 7 8 9 10 11 12 import lombok.Data;@Data @NoArgsConstructor @AllArgsConstructor public class User { private Integer id; private String name; private Short age; private Short gender; private String phone; }
Lombok的注意事项:
Lombok会在编译时,会自动生成对应的java代码
在使用lombok时,还需要安装一个lombok的插件(新版本的IDEA中自带)
5. Mybatis基础操作 5.1 准备 实施前的准备工作:
准备数据库表
创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok)
application.properties中引入数据库连接信息
创建对应的实体类 Emp(实体类属性采用驼峰命名)
准备Mapper接口 EmpMapper
创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok)
application.properties中引入数据库连接信息
提示:可以把之前项目中已有的配置信息复制过来即可
1 2 3 4 5 6 7 8 spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver spring.datasource.url =jdbc:mysql://localhost:3306/mybatis spring.datasource.username =root spring.datasource.password =123456
创建对应的实体类Emp(实体类属性采用驼峰命名)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Data @NoArgsConstructor @AllArgsConstructor public class Emp { private Integer id; private String username; private String password; private String name; private Short gender; private String image; private Short job; private LocalDate entrydate; private Integer deptId; private LocalDateTime createTime; private LocalDateTime updateTime; }
准备Mapper接口:EmpMapper
1 2 3 4 5 6 7 @Mapper public interface EmpMapper {}
5.2 删除 5.2.1 功能实现 功能:根据主键删除数据
1 2 -- 删除id=17的数据 delete from emp where id = 17;
Mybatis框架让程序员更关注于SQL语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @Mapper public interface EmpMapper { @Delete("delete from emp where id = #{id}") public void delete (Integer id) ; }
@Delete注解:用于编写delete操作的SQL语句
如果mapper接口方法形参只有一个普通类型的参数,#{…} 里面的属性名可以随便写,如:#{id}、#{value}。但是建议保持名字一致。
测试
在单元测试类中通过@Autowired注解注入EmpMapper类型对象
1 2 3 4 5 6 7 8 9 10 11 12 @SpringBootTest class SpringbootMybatisCrudApplicationTests { @Autowired private EmpMapper empMapper; @Test public void testDel () { empMapper.delete(16 ); } }
5.2.2 日志输出 在Mybatis当中我们可以借助日志,查看到sql语句的执行、执行传递的参数以及执行结果。具体操作如下:
打开application.properties文件
开启mybatis的日志,并指定输出到控制台
1 2 mybatis.configuration.log-impl =org.apache.ibatis.logging.stdout.StdOutImpl
但是我们发现输出的SQL语句:delete from emp where id = ?,我们输入的参数16并没有在后面拼接,id的值是使用?进行占位。那这种SQL语句我们称为预编译SQL。
5.2.3 预编译SQL 预编译SQL有两个优势:
性能更高
更安全(防止SQL注入)
性能更高:预编译SQL,编译一次之后会将编译后的SQL语句缓存起来,后面再次执行这条语句时,不会再次编译。(只是输入的参数不同)
更安全(防止SQL注入):将敏感字进行转义,保障SQL的安全性。
SQL注入:是通过操作输入的数据来修改事先定义好的SQL语句,以达到执行代码对服务器进行攻击的方法。
5.3 新增 5.3.1 基本新增 SQL语句:
1 insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) values ('songyuanqiao' ,'宋远桥' ,1 ,'1.jpg' ,2 ,'2012-10-09' ,2 ,'2022-10-01 10:00:00' ,'2022-10-01 10:00:00' );
接口方法:
1 2 3 4 5 6 7 @Mapper public interface EmpMapper { @Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) values (#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime})") public void insert (Emp emp) ; }
说明:#{…} 里面写的名称是对象的属性名
测试类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import com.itheima.mapper.EmpMapper;import com.itheima.pojo.Emp;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import java.time.LocalDate;import java.time.LocalDateTime;@SpringBootTest class SpringbootMybatisCrudApplicationTests { @Autowired private EmpMapper empMapper; @Test public void testInsert () { Emp emp = new Emp (); emp.setUsername("tom" ); emp.setName("汤姆" ); emp.setImage("1.jpg" ); emp.setGender((short )1 ); emp.setJob((short )1 ); emp.setEntrydate(LocalDate.of(2000 ,1 ,1 )); emp.setCreateTime(LocalDateTime.now()); emp.setUpdateTime(LocalDateTime.now()); emp.setDeptId(1 ); empMapper.insert(emp); } }
5.3.2 主键返回 概念:在数据添加成功后,需要获取插入数据库数据的主键
那要如何实现在插入数据之后返回所插入行的主键值呢?
默认情况下,执行插入操作时,是不会主键值返回的。如果我们想要拿到主键值,需要在Mapper接口中的方法上添加一个Options注解,并在注解中指定属性useGeneratedKeys=true和keyProperty=”实体类属性名”
主键返回代码实现:
1 2 3 4 5 6 7 8 @Mapper public interface EmpMapper { @Options(useGeneratedKeys = true,keyProperty = "id") @Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) values (#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime})") public void insert (Emp emp) ; }
测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 @SpringBootTest class SpringbootMybatisCrudApplicationTests { @Autowired private EmpMapper empMapper; @Test public void testInsert () { Emp emp = new Emp (); emp.setUsername("jack" ); emp.setName("杰克" ); emp.setImage("1.jpg" ); emp.setGender((short )1 ); emp.setJob((short )1 ); emp.setEntrydate(LocalDate.of(2000 ,1 ,1 )); emp.setCreateTime(LocalDateTime.now()); emp.setUpdateTime(LocalDateTime.now()); emp.setDeptId(1 ); empMapper.insert(emp); System.out.println(emp.getDeptId()); } }
5.4 更新 SQL语句:
1 update emp set username = 'linghushaoxia' , name = '令狐少侠' , gender = 1 , image = '1.jpg' , job = 2 , entrydate = '2012-01-01' , dept_id = 2 , update_time = '2022-10-01 12:12:12' where id = 18 ;
接口方法:
1 2 3 4 5 6 7 8 9 10 @Mapper public interface EmpMapper { @Update("update emp set username=#{username}, name=#{name}, gender=#{gender}, image=#{image}, job=#{job}, entrydate=#{entrydate}, dept_id=#{deptId}, update_time=#{updateTime} where id=#{id}") public void update (Emp emp) ; }
测试类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 @SpringBootTest class SpringbootMybatisCrudApplicationTests { @Autowired private EmpMapper empMapper; @Test public void testUpdate () { Emp emp = new Emp (); emp.setId(23 ); emp.setUsername("songdaxia" ); emp.setPassword(null ); emp.setName("老宋" ); emp.setImage("2.jpg" ); emp.setGender((short )1 ); emp.setJob((short )2 ); emp.setEntrydate(LocalDate.of(2012 ,1 ,1 )); emp.setCreateTime(null ); emp.setUpdateTime(LocalDateTime.now()); emp.setDeptId(2 ); empMapper.update(emp); } }
5.5 查询 5.5.1 根据ID查询 SQL语句:
1 select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp;
接口方法:
1 2 3 4 5 @Mapper public interface EmpMapper { @Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id=#{id}") public Emp getById (Integer id) ; }
测试类:
1 2 3 4 5 6 7 8 9 10 11 @SpringBootTest class SpringbootMybatisCrudApplicationTests { @Autowired private EmpMapper empMapper; @Test public void testGetById () { Emp emp = empMapper.getById(1 ); System.out.println(emp); } }
而在测试的过程中,我们会发现有几个字段(deptId、createTime、updateTime)是没有数据值的
5.5.2 数据封装
实体类属性名和数据库表查询返回的字段名一致,mybatis会自动封装。
如果实体类属性名和数据库表查询返回的字段名不一致,不能自动封装。
解决方案:
起别名
结果映射
开启驼峰命名
起别名 :在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样
1 2 3 4 5 @Select("select id, username, password, name, gender, image, job, entrydate, " + "dept_id AS deptId, create_time AS createTime, update_time AS updateTime " + "from emp " + "where id=#{id}") public Emp getById (Integer id) ;
手动结果映射 :通过 @Results及@Result 进行手动结果映射
1 2 3 4 5 @Results({@Result(column = "dept_id", property = "deptId"), @Result(column = "create_time", property = "createTime"), @Result(column = "update_time", property = "updateTime")}) @Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id=#{id}") public Emp getById (Integer id) ;
@Results源代码:
1 2 3 4 5 6 7 8 @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface Results {String id () default "" ; Result[] value() default {}; }
@Result源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) @Repeatable(Results.class) public @interface Result {boolean id () default false ;String column () default "" ; String property () default "" ; Class<?> javaType() default void .class; JdbcType jdbcType () default JdbcType.UNDEFINED; Class<? extends TypeHandler > typeHandler() default UnknownTypeHandler.class; One one () default @One ; Many many () default @Many ; }
**开启驼峰命名(推荐)**:如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射
驼峰命名规则: abc_xyz => abcXyz
表中字段名:abc_xyz
类中属性名:abcXyz
1 2 mybatis.configuration.map-underscore-to-camel-case =true
要使用驼峰命名前提是 实体类的属性 与 数据库表中的字段名严格遵守驼峰命名。
5.2.3 条件查询 SQL语句:
1 2 3 4 5 6 select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where name like '%张%' and gender = 1 and entrydate between '2010-01-01' and '2020-01-01 ' order by update_time desc ;
接口方法:
1 2 3 4 5 6 7 8 9 @Mapper public interface EmpMapper { @Select("select * from emp " + "where name like '%${name}%' " + "and gender = #{gender} " + "and entrydate between #{begin} and #{end} " + "order by update_time desc") public List<Emp> list (String name, Short gender, LocalDate begin, LocalDate end) ; }
以上方式注意事项:
方法中的形参名和SQL语句中的参数占位符名保持一致
模糊查询使用${…}进行字符串拼接,这种方式呢,由于是字符串拼接,并不是预编译的形式,所以效率不高、且存在sql注入风险。
方式二(解决SQL注入风险)
使用MySQL提供的字符串拼接函数:concat(‘%’ , ‘关键字’ , ‘%’)
1 2 3 4 5 6 7 8 9 10 11 12 @Mapper public interface EmpMapper { @Select("select * from emp " + "where name like concat('%',#{name},'%') " + "and gender = #{gender} " + "and entrydate between #{begin} and #{end} " + "order by update_time desc") public List<Emp> list (String name, Short gender, LocalDate begin, LocalDate end) ; }
执行结果:生成的SQL都是预编译的SQL语句(性能高、安全)
5.2.4 参数名说明 6. Mybatis的XML配置文件 Mybatis的开发有两种方式:
注解
XML
6.1 XML配置文件规范 使用Mybatis的注解方式,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句,也就是将SQL语句写在XML配置文件中。
在Mybatis中使用XML映射文件方式开发,需要符合一定的规范:
XML映射文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包下(同包同名)
XML映射文件的namespace属性为Mapper接口全限定名一致
XML映射文件中sql语句的id与Mapper接口中的方法名一致,并保持返回类型一致。
<select>标签:就是用于编写select查询语句的。
resultType属性,指的是查询返回的单条记录所封装的类型。
6.2 XML配置文件实现 第1步:创建XML映射文件
第2步:编写XML映射文件
xml映射文件中的dtd约束,直接从mybatis官网复制即可
1 2 3 4 5 6 7 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace ="" > </mapper >
配置:XML映射文件的namespace属性为Mapper接口全限定名
1 2 3 4 5 6 7 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace ="com.itheima.mapper.EmpMapper" > </mapper >
配置:XML映射文件中sql语句的id与Mapper接口中的方法名一致,并保持返回类型一致
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace ="com.itheima.mapper.EmpMapper" > <select id ="list" resultType ="com.itheima.pojo.Emp" > select * from emp where name like concat('%',#{name},'%') and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc </select > </mapper >
6.3 MybatisX的使用 MybatisX是一款基于IDEA的快速开发Mybatis的插件,为效率而生。
可以通过MybatisX快速定位
使用Mybatis的注解,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句。
7.Mybatis动态SQL 7.1 什么是动态SQL SQL语句会随着用户的输入或外部条件的变化而变化,我们称为:动态SQL 。
在Mybatis中提供了很多实现动态SQL的标签,我们学习Mybatis中的动态SQL就是掌握这些动态SQL标签。
7.2 动态SQL-if <if>
:用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL。
1 2 3 <if test ="条件表达式" > 要拼接的sql语句 </if >
接下来,我们就通过<if>
标签来改造之前条件查询的案例。
7.2.1 条件查询 示例:把SQL语句改造为动态SQL方式
1 2 3 4 5 6 7 <select id ="list" resultType ="com.itheima.pojo.Emp" > select * from emp where name like concat('%',#{name},'%') and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc </select >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <select id ="list" resultType ="com.itheima.pojo.Emp" > select * from emp where <if test ="name != null" > name like concat('%',#{name},'%') </if > <if test ="gender != null" > and gender = #{gender} </if > <if test ="begin != null and end != null" > and entrydate between #{begin} and #{end} </if > order by update_time desc </select >
测试方法:
1 2 3 4 5 6 7 8 @Test public void testList () { List<Emp> list = empMapper.list("张" , null , null , null ); for (Emp emp : list){ System.out.println(emp); } }
以上问题的解决方案:使用<where>
标签代替SQL语句中的where关键字
<where>
只会在子元素有内容的情况下才插入where子句,而且会自动去除子句的开头的AND或OR
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <select id ="list" resultType ="com.itheima.pojo.Emp" > select * from emp <where > <if test ="name != null" > and name like concat('%',#{name},'%') </if > <if test ="gender != null" > and gender = #{gender} </if > <if test ="begin != null and end != null" > and entrydate between #{begin} and #{end} </if > </where > order by update_time desc </select >
测试方法:
1 2 3 4 5 6 7 8 @Test public void testList () { List<Emp> list = empMapper.list(null , (short )1 , null , null ); for (Emp emp : list){ System.out.println(emp); } }
7.2.2 更新员工 案例:完善更新员工功能,修改为动态更新员工数据信息
动态更新员工信息,如果更新时传递有值,则更新;如果更新时没有传递值,则不更新
解决方案:动态SQL
修改Mapper接口:
1 2 3 4 5 6 @Mapper public interface EmpMapper { public void update (Emp emp) ; }
修改Mapper映射文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace ="com.itheima.mapper.EmpMapper" > <update id ="update" > update emp set <if test ="username != null" > username=#{username}, </if > <if test ="name != null" > name=#{name}, </if > <if test ="gender != null" > gender=#{gender}, </if > <if test ="image != null" > image=#{image}, </if > <if test ="job != null" > job=#{job}, </if > <if test ="entrydate != null" > entrydate=#{entrydate}, </if > <if test ="deptId != null" > dept_id=#{deptId}, </if > <if test ="updateTime != null" > update_time=#{updateTime} </if > where id=#{id} </update > </mapper >
测试方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 @Test public void testUpdate2 () { Emp emp = new Emp (); emp.setId(20 ); emp.setUsername("Tom111" ); emp.setName("汤姆111" ); emp.setUpdateTime(LocalDateTime.now()); empMapper.update(emp); }
执行的SQL语句:
再次修改测试方法,观察SQL语句执行情况:
1 2 3 4 5 6 7 8 9 10 @Test public void testUpdate2 () { Emp emp = new Emp (); emp.setId(20 ); emp.setUsername("Tom222" ); empMapper.update(emp); }
执行的SQL语句,多出一个逗号
以上问题的解决方案:使用<set>
标签代替SQL语句中的set关键字
<set>
:动态的在SQL语句中插入set关键字,并会删掉额外的逗号。(用于update语句中)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace ="com.itheima.mapper.EmpMapper" > <update id ="update" > update emp <set > <if test ="username != null" > username=#{username}, </if > <if test ="name != null" > name=#{name}, </if > <if test ="gender != null" > gender=#{gender}, </if > <if test ="image != null" > image=#{image}, </if > <if test ="job != null" > job=#{job}, </if > <if test ="entrydate != null" > entrydate=#{entrydate}, </if > <if test ="deptId != null" > dept_id=#{deptId}, </if > <if test ="updateTime != null" > update_time=#{updateTime} </if > </set > where id=#{id} </update > </mapper >
小结
<if>
<where>
where元素只会在子元素有内容的情况下才插入where子句,而且会自动去除子句的开头的AND或OR
<set>
动态地在行首插入 SET 关键字,并会删掉额外的逗号。(用在update语句中)
7.3 动态SQL-foreach 案例:员工删除功能(既支持删除单条记录,又支持批量删除)
SQL语句:
1 delete from emp where id in (1,2,3);
Mapper接口:
1 2 3 4 5 @Mapper public interface EmpMapper { public void deleteByIds (List<Integer> ids) ; }
XML映射文件:
使用<foreach>
遍历deleteByIds方法中传递的参数ids集合
1 2 3 <foreach collection ="集合名称" item ="集合遍历出来的元素/项" separator ="每一次遍历使用的分隔符" open ="遍历开始前拼接的片段" close ="遍历结束后拼接的片段" > </foreach >
1 2 3 4 5 6 7 8 9 10 11 12 13 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace ="com.itheima.mapper.EmpMapper" > <delete id ="deleteByIds" > delete from emp where id in <foreach collection ="ids" item ="id" separator ="," open ="(" close =")" > #{id} </foreach > </delete > </mapper >
7.4 动态SQL-sql&include 问题分析:
在xml映射文件中配置的SQL,有时可能会存在很多重复的片段,此时就会存在很多冗余的代码
我们可以对重复的代码片段进行抽取,将其通过<sql>
标签封装到一个SQL片段,然后再通过<include>
标签进行引用。
SQL片段: 抽取重复的代码
1 2 3 <sql id ="commonSelect" > select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp </sql >
然后通过<include>
标签在原来抽取的地方进行引用。操作如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <select id ="list" resultType ="com.itheima.pojo.Emp" > <include refid ="commonSelect" /> <where > <if test ="name != null" > name like concat('%',#{name},'%') </if > <if test ="gender != null" > and gender = #{gender} </if > <if test ="begin != null and end != null" > and entrydate between #{begin} and #{end} </if > </where > order by update_time desc </select >