JavaWeb回顾与小结(五)
Mybatis基础操作
环境准备工作
- 准备数据库表
- 创建一个新的springboot工程,选择引入对应的起步依赖(mybatis,mysql驱动,lombok)
- application.properties中引入数据库连接信息
- 创建对应的实体类Emp(实体类属性采用驼峰命名)
- 准备Mapper接口EmpMapper
根据主键删除
SQL语句
delete from emp where id = 17;
接口方法
@Delete("delete from emp where id = #{id}")
public void delete(Integer id);
注意事项
- 如果mapper接口方法形参只有一个普通类型的参数,#{...}里面的属性名可以随便写,如:
#{id},#{value}
日志输出
可以在application.properties中,打开mybatis的日志,并指定输出到控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
预编译SQL
性能更高
更安全(防止SQL注入漏洞)
SQL注入是通过操作输入的数据来修改事先定义好的SQL语句,以达到执行代码对服务器进行攻击的方法
参数占位符
#{...}
- 执行SQL时,会将#{...}替换为?,生成预编译SQL,会自动设置参数值
- 使用场景:参数传递,都使用#
${...}
- 拼接SQL,直接将参数拼接在SQL语句中,存在SQL注入漏洞问题
- 使用场景:如果对表名,列表进行动态设置时使用(使用很少)
新增信息(主键返回)
SQL语句
insert into emp(username,name,gender,dept_id) values ('songyuanqiao','宋远桥',1,2)
接口方法
@Insert("insert into emp(username,name,gender,dept_id)"+"values(#{username},#{name},#{gender},#{dept_id})")
public void insert (Emp emp);
主键返回
@Option(useGenratedKeys=true,keyProperty="id")
会自动将生成的主键值,赋值给参数对象的id属性
根据主键更新
SQL语句
update emp set username='songdaxia',name='宋大侠',gender=1,dept_id=2 where id = 19;
接口方法
@Update("update emp set username=#{username},name=#{name},gender=#{gender},dept_id=#{deptId} where id=#{id}")
public void update (Emp emp);
根据主键查询
SQL语句
select * from emp where id = 19;
接口方法
@Select("select * from emp where id = #{id}")
public Emp getById(Integer id);
数据封装
- 实体类属性名和数据库表查询返回的字段名一致,mybatis会自动封装
- 如果实体类属性名和数据库表查询返回的字段名不一致,不能自动封装
- 三种解决方法
- 起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样
- 手动结果映射:通过@Results及@Result进行手动结果映射
@Select("select * from emp where id =#{id}")
@Results({
@Result(column="dept_id",property="deptId"),
@Result(column="create_time",property="createTime"),
@Result(column="update_time",property="updateTime")})
public Emp getById(Integer id);
- 开启驼峰命名:如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射
开启自动映射
mybatis.configuration.map-underscore-to-camel-case=true
根据条件查询
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;
接口方法
@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);
注意
- MySQL中concat函数,使用方法:concat(str1,str2, ...)
- 返回结果为连接参数产生的字符串
XML映射文件
规范
- XML映射文件的名称与Mapper接口名称一致,并且XML映射文件的目录结构和Mapper接口的包结构相同(同名同位置)
- XML映射文件的namespace属性为Mapper接口全限定名一致
- XML映射文件中sql语句的id与Mapper接口中的方法名一致
XML映射文件---MybatisX插件的安装和使用
- 简单的增删改查操作使用注解配置SQL,复杂的操作使用xml映射文件配置SQL
- 如果xml映射文件和Mapper接口没有同名同位置,需要在application.properties属性文件中指定xml映射配置文件的位置
Mybatis动态SQL
<if>标签
<where>
<where>:代替where关键字,如果没有条件则不会被翻译成where关键字- 自动去除多余的and或者or
<if>
用于判断条件是否成立,使用test属性进行条件判断,如果条件为true,则拼接SQL
<set>
代替set关键字,并会删掉额外的逗号,用在update语句中
<foreach>
SQL语句
delete from emp where id in (1,2,3);
接口方法
public void deleteByIds(List<Integer> ids);
XML映射文件
<delete id = "deleteByIds">
delete from emp where id in
<foreach collection-"ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
- collection:被遍历的集合/数组名称
- item:集合遍历出来的元素在,使用#{}引用
- separator:每一次遍历使用的分隔符
- open:遍历开始前拼接的片段
- close:遍历结束后拼接的片段
<sql><include>
<sql>:定义可重用的SQL片段<include>:通过属性refid,指定包含的sql片段
项目实战
准备工作
功能介绍&环境搭建
- 准备数据库表
- 创建springboot工程,引入对应的起步依赖(web,mybatis,mysql驱动,lombok)
- 配置文件application.properties中引入mybatis的配置信息,准备对应的实体类
- 准备对应的Mapper,Service(接口,实现类),Controller基础结构
Restful开发规范
风格
- GET:查询id为1的用户
- POST:新增用户
- PUT:修改用户
- DELETE:删除id为1的用户
注意事项
- RESTful是一种风格,是约定的方式,约定不是规定,可以打破
- 描述模块的功能通常使用复数,也就是加s的格式来描述,表示此类资源,而非单个资源,如user,emps,books
开发流程
- 查看页面原型,明确需求
- 阅读接口文档
- 思路分析
- 接口开发
- 接口测试
- 前后端联调
部门管理
查询思路
思路
- 调用service查询部门,响应Result
controller - 调用mapper接口查询
service - select * from dept;
mapper
前后端联调
(略)
删除部门
思路
- 接收请求参数id,调用service删除部门,响应result
@DeleteMapping
@PathVariable - 调用mapper接口执行删除操作
- delete from dept where id = ?;
新增部门
思路
- 接收请求参数,调用service新增部门,响应result
@PostMapping
@RequestBody - 补充基础属性(创建时间,修改时间),调用mapper接口执行新增操作
- insert into dept values(?,?,?);
一个完整的请求路径,应该是类上的@RequestMapping的value属性+方法上的@RequestMapping的value属性
员工管理
分页查询
分页插件PageHelper
- 起步依赖
pagehelper-spring-boot-starter - mapper
由插件在sql后面添加limit分页 - service实现类
- 设置分页参数
PageHelper.startPage(pageNum:1, pageSize:2); - 分页查询
Page<Emp> page = (Page<Emp>)empMapper.list(); - 获取分页结果
log.info("总记录数:{}",page.getTotal());
log.info("当前页数据:{}",page.getResult());
思路
- 接收分页参数page,pageSize(设置默认值),调用service进行分页查询,获取PageBean,响应Result
- 设置分页参数,调用mapper接口分页查询,获取结果,封装成PageBean对象返回
- select * from emp order by update_time desc;
@RequestParam的属性defaultValue可以来设置参数的默认值
分页查询(带条件)
思路
- 接收参数(分页参数,查询条件),调用service进行分页条件查询,获取PageBean,响应Result
- 调用Mapper接口方法,使用PageHelper完成分页条件查询,封装PageBean对象返回
select * from emp ... order by update_time desc;
删除员工
思路
- 接收路径参数id数组,调用service进行批量删除,响应Result
@DeleteMapping
@PathVariable - 调用mapper接口进行批量删除操作
delete from emp
where id in (?,?,?);
<foreach>

浙公网安备 33010602011771号