当前位置: 首页 > news >正文

Mybatis—基础操作

mybatis入门后,继续学习mybatis基础操作。

目录

  • Mybatis基础操作
    • 准备工作
    • 删除操作
      • 日志输入
      • 预编译SQL
        • SQL注入
        • 参数占位符
    • 新增操作
      • 基本新增
      • 添加后返回主键
    • 更新操作
    • 查询操作
      • 根据id查询
      • 数据封装
      • 条件查询
      • 条件查询

Mybatis基础操作

准备工作

根据下面页面原型及需求,完成员工管理的需求开发。

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

通过分析以上的页面原型和需求,我们确定了功能列表:

1. 查询根据主键ID查询条件查询
2. 新增
3. 更新
4. 删除根据主键ID删除根据主键ID批量删除

准备工作:

1. 准备数据库表
2. 创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok)
3. application.properties中引入数据库连接信息
4. 创建对应的实体类 Emp(实体类属性采用驼峰命名)
5. 准备Mapper接口 EmpMapper

数据库sql:

-- 部门管理
create table dept
(id          int unsigned primary key auto_increment comment '主键ID',name        varchar(10) not null unique comment '部门名称',create_time datetime    not null comment '创建时间',update_time datetime    not null comment '修改时间'
) comment '部门表';
-- 部门表测试数据
insert into dept (id, name, create_time, update_time)
values (1, '学工部', now(), now()),(2, '教研部', now(), now()),(3, '咨询部', now(), now()),(4, '就业部', now(), now()),(5, '人事部', now(), now());-- 员工管理
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(实体类属性采用驼峰命名)

@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;     //LocalDate类型对应数据表中的date类型private Integer deptId;private LocalDateTime createTime;//LocalDateTime类型对应数据表中的datetime类型private LocalDateTime updateTime;
}

Mapper接口:EmpMapper

/*@Mapper注解:表示当前接口为mybatis中的Mapper接口程序运行时会自动创建接口的实现类对象(代理对象),并交给Spring的IOC容器管理
*/
@Mapper
public interface EmpMapper {}



删除操作

页面原型:

在这里插入图片描述

当我们点击后面的"删除"按钮时,前端页面会给服务端传递一个参数,也就是该行数据的ID。
我们接收到ID后,根据ID删除数据即可。

@Mapper
public interface EmpMapper {//@Delete注解:用于编写delete操作的SQL语句//@Delete("delete from emp where id = 17")//public void delete();//以上delete操作的SQL语句中的id值写成固定的17,就表示只能删除id=17的用户数据//SQL语句中的id值不能写成固定数值,需要变为动态的数值//解决方案:在delete方法中添加一个参数(用户id),将方法中的参数,传给SQL语句/*** 根据id删除数据* @param id    用户id*/@Delete("delete from emp where id = #{id}")//使用#{key}方式获取方法中的参数值//如果mapper接口方法形参只有一个普通类型的参数,#{…} 里面的属性名可以随便写,如:#{id}、#{value}。但是建议保持名字一致。public void delete(Integer id);}

测试,在单元测试类中通过@Autowired注解注入EmpMapper类型对象

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {@Autowired //从Spring的IOC容器中,获取类型是EmpMapper的对象并注入private EmpMapper empMapper;@Testpublic void testDel(){//调用删除方法empMapper.delete(16);}}


日志输入

在Mybatis当中我们可以借助日志,查看到sql语句的执行、执行传递的参数以及执行结果。具体操作
如下:

  1. 打开application.properties文件
  2. 开启mybatis的日志,并指定输出到控制台
#指定mybatis输出日志的位置, 输出控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

开启日志之后,我们再次运行单元测试,可以看到在控制台中,输出了以下的SQL语句信息:

在这里插入图片描述

但是我们发现输出的SQL语句:delete from emp where id = ?,我们输入的参数16并没有在后面拼接,id的值是使用?进行占位。那这种SQL语句我们称为预编译SQL。



预编译SQL

预编译SQL有两个优势:

  1. 性能更高:预编译SQL,编译一次之后会将编译后的SQL语句缓存起来,后面再次执行这条语句时,不会再次编译。(只是输入的参数不同)
  2. 更安全(防止SQL注入):将敏感字进行转义,保障SQL的安全性。

在这里插入图片描述


SQL注入

SQL注入:是通过操作输入的数据来修改事先定义好的SQL语句,以达到执行代码对服务器进行攻击的方法。

由于没有对用户输入进行充分检查,而SQL又是拼接而成,在用户输入参数时,在参数中添加一些SQL关键字,达到改变SQL运行结果的目的,也可以完成恶意攻击。

在这里插入图片描述

在这里插入图片描述

使用预编译则无法注入:

在这里插入图片描述

把整个’ or ‘1’='1 作为一个完整的参数,赋值给第2个问号( ’ or ‘1’='1 进行了转义,只当做字符串使用)


参数占位符

在Mybatis中提供的参数占位符有两种:${…} 、#{…}

#{…}
执行SQL时,会将#{…}替换为?,生成预编译SQL,会自动设置参数值
使用时机:参数传递,都使用#{…}

${…}
拼接SQL。直接将参数拼接在SQL语句中,存在SQL注入问题
使用时机:如果对表名、列表进行动态设置时使用

在项目开发中,建议使用#{…},生成预编译SQL,防止SQL注入安全。




新增操作

基本新增

SQL语句:

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');

接口方法:

@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);}

说明:#{…} 里面写的名称是对象的属性名。实体类的属性名与表中的字段名一一对应。

测试类:

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {@Autowiredprivate EmpMapper empMapper;@Testpublic 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);//没有指定id和password//调用添加方法empMapper.insert(emp);}
}

在这里插入图片描述



添加后返回主键

在数据添加成功后,需要获取插入数据库数据的主键,则需要在Mapper接口中的方法上添加一个Options注解,并在注解中指定属性useGeneratedKeys=true和keyProperty=“实体类属性名”

主键返回代码实现:

@Mapper
public interface EmpMapper {//会自动将生成的主键值,赋值给emp对象的id属性@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);}

测试:

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {@Autowiredprivate EmpMapper empMapper;@Testpublic 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);//没有指定id和password//调用添加方法empMapper.insert(emp);System.out.println(emp.getDeptId());}
}

useGeneratedKeys=true代表我们需要拿到生成的主键值,
keyProperty="id"代表我们获取到的组件最终会封装到emp对象的id属性当中。





更新操作

功能:修改员工信息

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;

接口方法:

@Mapper
public interface EmpMapper {/*** 根据id修改员工信息* @param emp*/@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);}

测试类:

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {@Autowiredprivate EmpMapper empMapper;@Testpublic void testUpdate(){//修改后的员工信息Emp emp = new Emp();emp.setId(19);//修改id为19的员工信息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);}
}




查询操作

根据id查询

SQL语句:

select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp;

接口方法:

@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);
}

测试类:

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {@Autowiredprivate EmpMapper empMapper;@Testpublic void testGetById(){Emp emp = empMapper.getById(1);System.out.println(emp);}
}

在这里插入图片描述

测试会发现有几个字段(deptId、createTime、updateTime)是没有数据值的。



数据封装

deptId,createTime,updateTime这几个字段是没有值的,而数据库中是有对应的字段值的,这是为什么呢?

在这里插入图片描述

原因如下:

实体类属性名和数据库表查询返回的字段名一致,mybatis会自动封装。
如果实体类属性名和数据库表查询返回的字段名不一致,不能自动封装。

解决方案:

1. 起别名
2. 结果映射
3. 开启驼峰命名(推荐)

起别名 在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样

@Mapper
public interface EmpMapper {@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 进行手动结果映射

@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源代码:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Results {String id() default "";Result[] value() default {};  //Result类型的数组
}

@Result源代码:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Repeatable(Results.class)
public @interface Result {boolean id() default false;//表示当前列是否为主键(true:是主键)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

前提:

# 在application.properties中添加:
mybatis.configuration.map-underscore-to-camel-case=true# 实体类的属性 与 数据库表中的字段名严格遵守驼峰命名。



条件查询

通过页面原型以及需求描述我们要实现的查询:

姓名:要求支持模糊匹配
性别:要求精确匹配
入职时间:要求进行范围查询
根据最后修改时间进行降序排序

SQL语句:

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;

接口方法:

  • 方式一
@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);
}

测试:

@Testpublic void testGetById(){List<Emp> list = empMapper.list("张", (short) 1,LocalDate.of(2012,1,1),LocalDate.of(2020,1,1));System.out.println(list);}

以上方式注意事项:

1. 方法中的形参名和SQL语句中的参数占位符名保持一致
2. 由于在字符串中不能使用#{},所以使用了${},因为它是个字符串拼接符符号。
而模糊查询使用${...}进行字符串拼接,这种方式呢,由于是字符串拼接,并不是预编译的形式,所以效率不高、且存在sql注入风险。
  • 方式二(解决SQL注入风险)(推荐)
    • 使用MySQL提供的字符串拼接函数:concat(‘%’ , ‘关键字’ , ‘%’),concat可以拼接多个字符串。
@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语句(性能高、安全)




条件查询

在上面我们所编写的条件查询功能中,我们需要保证接口中方法的形参名和SQL语句中的参数占位符名相同。

当方法中的形参名和SQL语句中的占位符参数名不相同时,就会出现以下问题:

在这里插入图片描述

参数名在不同的SpringBoot版本中,处理方案还不同:

  • 在springBoot的2.x版本(保证参数名一致即可)

在这里插入图片描述

因为springBoot的父工程对compiler编译插件进行了默认的参数parameters配置,使得在编译时,会在生成的字节码文件中保留原方法形参的名称,所以#{…}里面可以直接通过相同的形参名获取对应的值

在这里插入图片描述



  • 在springBoot的1.x版本/单独使用mybatis(使用@Param注解来指定SQL语句中的参数名)

在这里插入图片描述

因为在编译时,生成的字节码文件当中,不会保留Mapper接口中方法的形参名称,而是使用var1、var2、…这样的形参名字,此时要获取参数值时,就要通过@Param注解来指定SQL语句中的参数名

在这里插入图片描述

相关文章:

  • 框架安全-CVE 漏洞复现DjangoFlaskNode.jsJQuery框架漏洞复现
  • ts 简易封装 axios,统一 API
  • 中国电子云-隐私计算-云原生安全可信计算,物理-硬件-系统-云产品-云平台,数据安全防护
  • Python Django 之模板语法详解
  • SpringMVC Day 11 : 零 xml 配置
  • Docker Tomcat 搭建文件服务器
  • 历年网规上午真题笔记(2016年)
  • 为什么汽车行业普遍选择使用CATIA?
  • lua-web-utils库
  • Java算法:二分查找
  • MPLAB X IDE 仿真打断点提示已中断的断点?
  • 十年JAVA搬砖路——Linux搭建Ldap服务器。
  • GaussDB SQL基础语法示例-数组表达式
  • 【Jenkins】新建任务FAQ
  • 软考高项-49个项目管理过程输入、输出和工具技术表
  • ECMAScript 6 学习之路 ( 四 ) String 字符串扩展
  • Java超时控制的实现
  • Laravel Telescope:优雅的应用调试工具
  • magento2项目上线注意事项
  • MySQL的数据类型
  • WebSocket使用
  • 阿里云容器服务区块链解决方案全新升级 支持Hyperledger Fabric v1.1
  • 百度地图API标注+时间轴组件
  • 开年巨制!千人千面回放技术让你“看到”Flutter用户侧问题
  • 码农张的Bug人生 - 见面之礼
  • 入门到放弃node系列之Hello Word篇
  • 设计模式走一遍---观察者模式
  • 协程
  • - 转 Ext2.0 form使用实例
  • TPG领衔财团投资轻奢珠宝品牌APM Monaco
  • 不要一棍子打翻所有黑盒模型,其实可以让它们发挥作用 ...
  • ​Python 3 新特性:类型注解
  • (PyTorch)TCN和RNN/LSTM/GRU结合实现时间序列预测
  • (超简单)使用vuepress搭建自己的博客并部署到github pages上
  • (附源码)springboot码头作业管理系统 毕业设计 341654
  • (附源码)计算机毕业设计大学生兼职系统
  • (四)【Jmeter】 JMeter的界面布局与组件概述
  • (四)docker:为mysql和java jar运行环境创建同一网络,容器互联
  • (四)七种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (转)linux自定义开机启动服务和chkconfig使用方法
  • (转)创业家杂志:UCWEB天使第一步
  • .bat批处理(七):PC端从手机内复制文件到本地
  • .Net 6.0 处理跨域的方式
  • .Net Attribute详解(上)-Attribute本质以及一个简单示例
  • .NET 事件模型教程(二)
  • .NET教程 - 字符串 编码 正则表达式(String Encoding Regular Express)
  • .NET命令行(CLI)常用命令
  • .NET设计模式(11):组合模式(Composite Pattern)
  • @Builder用法
  • @Mapper作用
  • [51nod1610]路径计数
  • [Android]使用Android打包Unity工程
  • [BZOJ 4598][Sdoi2016]模式字符串
  • [BZOJ1089][SCOI2003]严格n元树(递推+高精度)
  • [C#]winform部署PaddleOCRV3推理模型