1.查询(select)
- 根据ID查询
- 分页查询
- 新增(insert)
- 修改(update)
- 删除(delete)
- 根据主键ID删除
- 根据主键ID批量删除
2.准备
1. 创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok)
2. application.properties中引入数据库连接信息(复制过来即可)
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
3.准备数据库表 emp,及对应的实体类 Emp (实体类属性采用驼峰命名模式)
- SQL:
-- 创建数据库
create database if not exists mybatis;
-- 使用数据库
use mybatis;
-- 员工管理(带约束)
create table emp (
id int unsigned primary key auto_increment comment 'ID',
username varchar(20) not null unique comment '用户名',
password varchar(32) default '123456' comment '密码',
name varchar(10) not null comment '姓名',
gender tinyint unsigned not null comment '性别, 说明: 1 男, 2 女',
image varchar(300) comment '图像',
job tinyint unsigned comment '职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师',
entrydate date comment '入职时间',
dept_id int unsigned comment '部门ID',
create_time datetime not null comment '创建时间',
update_time datetime not null comment '修改时间'
) comment='员工表';
INSERT INTO emp
(id, username, password, name, gender, image, job, entrydate,dept_id, create_time, update_time) VALUES
(1,'jinyong','123456','金庸',1,'1.jpg',4,'2000-01-01',2,now(),now()),
(2,'zhangwuji','123456','张无忌',1,'2.jpg',2,'2015-01-01',2,now(),now()),
(3,'yangxiao','123456','杨逍',1,'3.jpg',2,'2008-05-01',2,now(),now()),
(4,'weiyixiao','123456','韦一笑',1,'4.jpg',2,'2007-01-01',2,now(),now()),
(5,'changyuchun','123456','常遇春',1,'5.jpg',2,'2012-12-05',2,now(),now()),
(6,'xiaozhao','123456','小昭',2,'6.jpg',3,'2013-09-05',1,now(),now()),
(7,'jixiaofu','123456','纪晓芙',2,'7.jpg',1,'2005-08-01',1,now(),now()),
(8,'zhouzhiruo','123456','周芷若',2,'8.jpg',1,'2014-11-09',1,now(),now()),
(9,'dingminjun','123456','丁敏君',2,'9.jpg',1,'2011-03-11',1,now(),now()),
(10,'zhaomin','123456','赵敏',2,'10.jpg',1,'2013-09-05',1,now(),now()),
(11,'luzhangke','123456','鹿杖客',1,'11.jpg',5,'2007-02-01',3,now(),now()),
(12,'hebiweng','123456','鹤笔翁',1,'12.jpg',5,'2008-08-18',3,now(),now()),
(13,'fangdongbai','123456','方东白',1,'13.jpg',5,'2012-11-01',3,now(),now()),
(14,'zhangsanfeng','123456','张三丰',1,'14.jpg',2,'2002-08-01',2,now(),now()),
(15,'yulianzhou','123456','俞莲舟',1,'15.jpg',2,'2011-05-01',2,now(),now()),
(16,'songyuanqiao','123456','宋远桥',1,'16.jpg',2,'2010-01-01',2,now(),now()),
(17,'chenyouliang','123456','陈友谅',1,'17.jpg',NULL,'2015-03-21',NULL,now(),now());
实体类Emp
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.time.LocalDateTime;
@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;
}
4. 准备Mapper接口 EmpMapper
@Mapper
public interface EmpMapper {
}
3删除
3.1功能实现
当我们点击 后面的 “删除” 按钮时,前端页面会给服务端传递一个参数,也就是该行数据的ID。 我们接收到ID后,根据ID删除数据即可。
对应的SQL:
delete from emp where id = 17;
接口方法:
@Mapper
public interface EmpMapper {
@Delete("delete from emp where id = #{id}")
public void delete(Integer id);
}
注意:
如果mapper接口方法形参只有一个普通类型的参数,#{…} 里面的属性名可以随便写,如:#{id}、#{value}。
测试
接下来,我们就可以直接在单元测试类中通过 @Autowired 注解 EmpMapper接口。 然后就可以直接调用其delete方法传递参数进行测试了。
@SpringBootTest
class SpringbootMybatisQuickstart2ApplicationTests {
@Autowired
private EmpMapper empMapper;
@Test
public void testDel(){
empMapper.delete(15);
}
}
3.2 日志输入
可以在application.properties中,打开mybatis的日志,并指定输出到控制台。
#指定mybatis输出日志的位置, 输出控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
3.3 预编译SQL
1.预编译的SQL,有两个优势:
- 性能更高
性能更高: 预编译SQL,编译一次之后会将编译后的SQL语句缓存起来,后面再次执行这条insert语句时,SQL语句一样,不会再次编译。 只是输入的参数不同。
- 防止SQL注入
防止SQL注入:将敏感字进行转义,安全。
2.SQL注入
SQL注入是通过操作输入来修改事先定义好的SQL语句,用以达到执行代码对服务器进行攻击的方法。
3.参数占位符
在Mybatis中提供的参数占位符有两种:${...}, #{...}。
1). #{...}
执行SQL时,会将#{…}替换为?,生成预编译SQL,会自动设置参数值。
使用时机:参数传递,都使用#{…}
2). ${...}
拼接SQL。直接将参数拼接在SQL语句中,存在SQL注入问题。
使用时机:如果对表名、列表进行动态设置时使用。
注意事项:
在项目开发中,建议使用#{...},生成预编译SQL,防止SQL注入安全。
4 新增
4.1.基本新增
1). SQL
insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) values ('linghuchong','令狐冲',1,'1.jpg',2,'2012-10-09',2,'2022-10-01 10:00:00','2022-10-01 10:00:00');
2). 接口方法
@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);
#{...} 里面写的名称是对象的属性。
3). 测试
@Test
public void testInsert(){
Emp emp = new Emp(null,"songyuanqiao2",null,"宋远桥2",(short)1,"1.jpg",(short)2, LocalDate.of(2012,10,10),2,LocalDateTime.now(),LocalDateTime.now());
empMapper.insert(emp);
System.out.println(emp.getId());
}
4.2.主键返回
含义:在数据添加成功后,需要获取插入数据库数据的主键。如:添加菜品口味
@Options(keyProperty = "id", useGeneratedKeys = true)
@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);
5.更新
1). SQL
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;
2). 接口方法
@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);
3). 单元测试
@Test
public void testUpdate(){
Emp emp = new Emp(19,"songdaxia",null,"宋大侠2",(short)1,"2.jpg",(short)2, LocalDate.of(2012,1,1),2,null,LocalDateTime.now());
empMapper.update(emp);
}
6 查询
6.1 根据ID查询
在员工管理的页面中,当我们进行更新数据时,我们会点击 “编辑” 按钮,然后此时会发送一个请求到服务端,会根据Id查询该员工信息,用于页面回显。
1). SQL
select * from emp where id = 19;
2). 接口方法
@Select("select * from emp where id = #{id}")
public Emp getById(Integer id);
3). 单元测试
@Test
public void testGetById(){
Emp emp = empMapper.getById(1);
System.out.println(emp);
}
而在测试的过程中,我们会发现有几个字段(deptId、createTime、updateTime)是没有封装上的。
6.2 数据封装
我们看到查询返回的结果中大部分字段是有值的,但是deptId,createTime,updateTime这几个字段是没有值的,而数据库中是有对应的字段值的,这是为什么呢?
原因如下:
- 实体类属性名 和 数据库表查询返回的字段名一致,mybatis会自动封装为实体类。
- 如果实体类属性名 和 数据库表查询返回的字段名不一致,不能自动封装。
可以通过以下方案解决:
1). 起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样。
@Select("select id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime from emp where id = #{id}")
public Emp getById(Integer id);
2). 手动结果映射:通过 @Results及@Result 进行手动结果映射。
@Results({@Result(column = "dept_id", property = "deptId"),
@Result(column = "create_time", property = "createTime"),
@Result(column = "update_time", property = "updateTime")})
@Select("select * from emp where id = #{id}")
public Emp getById(Integer id);
3). 开启驼峰命名(推荐):如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射。
#开启驼峰命名自动映射,即从经典数据库列名 a_column 映射到经典 Java 属性名 aColumn。
mybatis.configuration.map-underscore-to-camel-case=true
要使用驼峰命名前提是 实体类的属性 与 数据库表中的字段名严格遵守驼峰命名。
6.3 条件查询
在员工管理的列表页面中,我们需要根据条件查询员工信息,查询条件包括:姓名、性别、入职时间。
通过页面原型以及需求描述,我们可以看出:
- 姓名:要求支持模糊匹配
- 性别:要求精确匹配
- 入职时间:要求进行范围查询
并且要求根据最后修改时间进行倒序排序。
- SQL:
select * from emp where name like '%张%' and gender = 1 and entrydate between '2010-01-01' and '2020-01-01' order by update_time desc;
6.4 参数名说明
在springBoot的2.x版本之后,springBoot的父工程对compiler编译插件进行了默认的参数 parameters 配置,使得在编译时,会在字节码文件中保留原方法形参的名称,所以#{…}里面可以直接通过形参名获取对应的值。
在springBoot的1.x版本中,所有接口方法形参编译后的为var1、var2 …,此时如果有多个参数,就需要通过@Param注解来指定SQL语句中的参数名。
6.5 问题分析
在页面原型中,列表上方的条件是动态的,是可以不传递的,可以只是传递其中的一个 或者 两个 或者 三个。
而在我们刚才编写的SQL语句中,我们会看到,我们将三个条件直接写死了。 如果页面只传递了参数姓名 name 字段,其他两个字段 性别 和 入职时间没有传递,那么这两个参数的值就是null
此时,执行的SQL语句为:
这个查询结果是不正确的。正确的做法应该是,传递了参数,再组装这个查询条件。如果没有传递参数,就不应该组装这个查询条件。
就比如,如果姓名输入了:"张", 对应的SQL为:
select * from emp where name like '%张%' order by update_time desc;
如果如果姓名输入了:"张", 性别选择了: 男, 则对应的SQL为:
select * from emp where name like '%张%' and gender = 1 order by update_time desc;
那这种:SQL语句会随着用户的输入或外部条件的变化而变化,我们称为 动态SQL。