SpringBootWeb案例-1 -下

发布时间 2023-10-09 10:14:40作者: 伊吹萃香

3. 员工管理

完成了部门管理的功能开发之后,我们进入到下一环节员工管理功能的开发。

fig:

基于以上原型,我们可以把员工管理功能分为:

  1. 分页查询(今天完成)
  2. 带条件的分页查询(今天完成)
  3. 删除员工(今天完成)
  4. 新增员工(后续完成)
  5. 修改员工(后续完成)

那下面我们就先从分页查询功能开始学习。

3.1 分页查询

3.1.1 基础分页

3.1.1.1 需求分析

我们之前做的查询功能,是将数据库中所有的数据查询出来并展示到页面上,试想如果数据库中的数据有很多(假设有十几万条)的时候,将数据全部展示出来肯定不现实,那如何解决这个问题呢?

使用分页解决这个问题。每次只展示一页的数据,比如:一页展示10条数据,如果还想看其他的数据,可以通过点击页码进行查询。

fig:

要想从数据库中进行分页查询,我们要使用LIMIT关键字,格式为:limit 开始索引 每页显示的条数

查询第1页数据的SQL语句是:

select * from emp limit 0,10;

查询第2页数据的SQL语句是:

select * from emp limit 10,10;

查询第3页的数据的SQL语句是:

select * from emp limit 20,10;

观察以上SQL语句,发现: 开始索引一直在改变 , 每页显示条数是固定的

开始索引的计算公式: 开始索引 = (当前页码 - 1) * 每页显示条数

我们继续基于页面原型,继续分析,得出以下结论:

  1. 前端在请求服务端时,传递的参数
    • 当前页码 page
    • 每页显示条数 pageSize
  2. 后端需要响应什么数据给前端
    • 所查询到的数据列表(存储到List 集合中)
    • 总记录数

fig:

后台给前端返回的数据包含:List集合(数据列表)、total(总记录数)

而这两部分我们通常封装到PageBean对象中,并将该对象转换为json格式的数据响应回给浏览器。

@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageBean {
private Long total; //总记录数
private List rows; //当前页数据列表
}

3.1.1.2 接口文档

员工列表查询

  • 基本信息
  • 请求路径:/emps

    请求方式:GET

    接口描述:该接口用于员工列表数据的条件分页查询
  • 请求参数
  • 参数格式:queryString
  • 参数说明:

参数名称

是否必须

示例

备注

name

姓名

gender

1

性别 , 1 男 , 2 女

begin

2010-01-01

范围匹配的开始时间(入职日期)

end

2020-01-01

范围匹配的结束时间(入职日期)

page

1

分页查询的页码,如果未指定,默认为1

pageSize

10

分页查询的每页记录数,如果未指定,默认为10

  • 请求数据样例:
  • /emps?name=张&gender=1&begin=2007-09-01&end=2022-09-01&page=1&pageSize=10
  • 响应数据
  • 参数格式:application/json
  • 参数说明:

名称

类型

是否必须

默认值

备注

其他信息

code

number

必须

响应码, 1 成功 , 0 失败

msg

string

非必须

提示信息

data

object

必须

返回的数据

|- total

number

必须

总记录数

|- rows

object []

必须

数据列表

item 类型: object

|- id

number

非必须

id

|- username

string

非必须

用户名

|- name

string

非必须

姓名

|- password

string

非必须

密码

|- entrydate

string

非必须

入职日期

|- gender

number

非必须

性别 , 1 男 ; 2 女

|- image

string

非必须

图像

|- job

number

非必须

职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师

|- deptId

number

非必须

部门id

|- createTime

string

非必须

创建时间

|- updateTime

string

非必须

更新时间

  • 响应数据样例:
  • {
    "code": 1,
    "msg": "success",
    "data": {
    "total": 2,
    "rows": [
    {
    "id": 1,
    "username": "jinyong",
    "password": "123456",
    "name": "金庸",
    "gender": 1,
    "image": "https://web-framework.oss-cn-hangzhou.aliyuncs.com/2022-09-02-00-27-53B.jpg",
    "job": 2,
    "entrydate": "2015-01-01",
    "deptId": 2,
    "createTime": "2022-09-01T23:06:30",
    "updateTime": "2022-09-02T00:29:04"
    },
    {
    "id": 2,
    "username": "zhangwuji",
    "password": "123456",
    "name": "张无忌",
    "gender": 1,
    "image": "https://web-framework.oss-cn-hangzhou.aliyuncs.com/2022-09-02-00-27-53B.jpg",
    "job": 2,
    "entrydate": "2015-01-01",
    "deptId": 2,
    "createTime": "2022-09-01T23:06:30",
    "updateTime": "2022-09-02T00:29:04"
    }
    ]
    }
    }
3.1.1.3 思路分析

fig:

分页查询需要的数据,封装在PageBean对象中:

fig:

3.1.1.4 功能开发

通过查看接口文档:员工列表查询

请求路径:/emps

请求方式:GET

请求参数:跟随在请求路径后的参数字符串。 例:/emps?page=1&pageSize=10

响应数据:json格式

EmpController

import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {

@Autowired
private EmpService empService;

//条件分页查询
@GetMapping
public Result page(@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer pageSize) {
//记录日志
log.info("分页查询,参数:{},{}", page, pageSize);
//调用业务层分页查询功能
PageBean pageBean = empService.page(page, pageSize);
//响应
return Result.success(pageBean);
}
}

@RequestParam(defaultValue="默认值") //设置请求参数默认值

EmpService

public interface EmpService {
/**
* 条件分页查询
* @param page 页码
* @param pageSize 每页展示记录数
* @return
*/
PageBean page(Integer page, Integer pageSize);
}

EmpServiceImpl

import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBean;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.List;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
@Autowired
private EmpMapper empMapper;

@Override
public PageBean page(Integer page, Integer pageSize) {
//1、获取总记录数
Long count = empMapper.count();

//2、获取分页查询结果列表
Integer start = (page - 1) * pageSize; //计算起始索引 , 公式: (页码-1)*页大小
List<Emp> empList = empMapper.list(start, pageSize);

//3、封装PageBean对象
PageBean pageBean = new PageBean(count , empList);
return pageBean;
}
}

EmpMapper

@Mapper
public interface EmpMapper {
//获取总记录数
@Select("select count(*) from emp")
public Long count();

//获取当前页的结果列表
@Select("select * from emp limit #{start}, #{pageSize}")
public List<Emp> list(Integer start, Integer pageSize);
}

3.1.1.5 功能测试

功能开发完成后,重新启动项目,使用postman,发起POST请求:

fig:

3.1.1.6 前后端联调

打开浏览器,测试后端功能接口:

fig:

3.1.2 分页插件

3.1.2.1 介绍

前面我们已经完了基础的分页查询,大家会发现:分页查询功能编写起来比较繁琐。

fig:

在Mapper接口中定义两个方法执行两条不同的SQL语句:

  1. 查询总记录数
  2. 指定页码的数据列表

在Service当中,调用Mapper接口的两个方法,分别获取:总记录数、查询结果列表,然后在将获取的数据结果封装到PageBean对象中。

大家思考下:在未来开发其他项目,只要涉及到分页查询功能(例:订单、用户、支付、商品),都必须按照以上操作完成功能开发

结论:原始方式的分页查询,存在着"步骤固定"、"代码频繁"的问题

解决方案:可以使用一些现成的分页插件完成。对于Mybatis来讲现在最主流的就是PageHelper。

PageHelper是Mybatis的一款功能强大、方便易用的分页插件,支持任何形式的单标、多表的分页查询。

官网:https://pagehelper.github.io/

fig:

在执行empMapper.list()方法时,就是执行:select * from emp 语句,怎么能够实现分页操作呢?

分页插件帮我们完成了以下操作:

  1. 先获取到要执行的SQL语句:select * from emp
  2. 把SQL语句中的字段列表,变为:count(*)
  3. 执行SQL语句:select count(*) from emp //获取到总记录数
  4. 再对要执行的SQL语句:select * from emp 进行改造,在末尾添加 limit ? , ?
  5. 执行改造后的SQL语句:select * from emp limit ? , ?
3.1.2.2 代码实现

当使用了PageHelper分页插件进行分页,就无需再Mapper中进行手动分页了。 在Mapper中我们只需要进行正常的列表查询即可。在Service层中,调用Mapper的方法之前设置分页参数,在调用Mapper方法执行查询之后,解析分页结果,并将结果封装到PageBean对象中返回。

1、在pom.xml引入依赖

<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.2</version>
</dependency>

2、EmpMapper

@Mapper
public interface EmpMapper {
//获取当前页的结果列表
@Select("select * from emp")
public List<Emp> page(Integer start, Integer pageSize);
}

3、EmpServiceImpl

@Override
public PageBean page(Integer page, Integer pageSize) {
// 设置分页参数
PageHelper.startPage(page, pageSize);
// 执行分页查询
List<Emp> empList = empMapper.list(name,gender,begin,end);
// 获取分页结果
Page<Emp> p = (Page<Emp>) empList;
//封装PageBean
PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
return pageBean;
}

3.1.2.3 测试

功能开发完成后,我们重启项目工程,打开postman,发起GET请求,访问 :http://localhost:8080/emps?page=1&pageSize=5

fig:

后端程序SQL输出:

fig:

3.2 分页查询(带条件)

完了分页查询后,下面我们需要在分页查询的基础上,添加条件。

3.2.1 需求

fig:

通过员工管理的页面原型我们可以看到,员工列表页面的查询,不仅仅需要考虑分页,还需要考虑查询条件。 分页查询我们已经实现了,接下来,我们需要考虑在分页查询的基础上,再加上查询条件。

我们看到页面原型及需求中描述,搜索栏的搜索条件有三个,分别是:

  • 姓名:模糊匹配
  • 性别:精确匹配
  • 入职日期:范围匹配

select *
from emp
where
name like concat('%','张','%') -- 条件1:根据姓名模糊匹配
and gender = 1 -- 条件2:根据性别精确匹配
and entrydate = between '2000-01-01' and '2010-01-01' -- 条件3:根据入职日期范围匹配
order by update_time desc;

而且上述的三个条件,都是可以传递,也可以不传递的,也就是动态的。 我们需要使用前面学习的Mybatis中的动态SQL 。

3.2.2 思路分析

fig:

3.2.3 功能开发

通过查看接口文档:员工列表查询

请求路径:/emps

请求方式:GET

请求参数:

参数名称

是否必须

示例

备注

name

姓名

gender

1

性别 , 1 男 , 2 女

begin

2010-01-01

范围匹配的开始时间(入职日期)

end

2020-01-01

范围匹配的结束时间(入职日期)

page

1

分页查询的页码,如果未指定,默认为1

pageSize

10

分页查询的每页记录数,如果未指定,默认为10

在原有分页查询的代码基础上进行改造:

EmpController

@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {

@Autowired
private EmpService empService;

//条件分页查询
@GetMapping
public Result page(@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer pageSize,
String name, Short gender,
@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {
//记录日志
log.info("分页查询,参数:{},{},{},{},{},{}", page, pageSize,name, gender, begin, end);
//调用业务层分页查询功能
PageBean pageBean = empService.page(page, pageSize, name, gender, begin, end);
//响应
return Result.success(pageBean);
}
}

EmpService

public interface EmpService {
/**
* 条件分页查询
* @param page 页码
* @param pageSize 每页展示记录数
* @param name 姓名
* @param gender 性别
* @param begin 开始时间
* @param end 结束时间
* @return
*/
PageBean page(Integer page, Integer pageSize, String name, Short gender, LocalDate begin, LocalDate end);
}

EmpServiceImpl

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
@Autowired
private EmpMapper empMapper;

@Override
public PageBean page(Integer page, Integer pageSize, String name, Short gender, LocalDate begin, LocalDate end) {
//设置分页参数
PageHelper.startPage(page, pageSize);
//执行条件分页查询
List<Emp> empList = empMapper.list(name, gender, begin, end);
//获取查询结果
Page<Emp> p = (Page<Emp>) empList;
//封装PageBean
PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
return pageBean;
}
}

EmpMapper

@Mapper
public interface EmpMapper {
//获取当前页的结果列表
public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
}

EmpMapper.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.itheima.mapper.EmpMapper">

<!-- 条件分页查询 -->
<select id="list" resultType="com.itheima.pojo.Emp">
select * from emp
<where>
<if test="name != null and name != ''">
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>
</mapper>

3.2.4 功能测试

功能开发完成后,重启项目工程,打开postman,发起GET请求:

fig:

控制台SQL语句:

fig:

3.2.5 前后端联调

打开浏览器,测试后端功能接口:

fig:

3.3 删除员工

查询员完成之后,我们继续开发新的功能:删除员工。

3.3.1 需求

fig:

当我们勾选列表前面的复选框,然后点击 "批量删除" 按钮,就可以将这一批次的员工信息删除掉了。也可以只勾选一个复选框,仅删除一个员工信息。

问题:我们需要开发两个功能接口吗?一个删除单个员工,一个删除多个员工

答案:不需要。 只需要开发一个功能接口即可(删除多个员工包含只删除一个员工)

3.3.2 接口文档

删除员工

  • 基本信息
  • 请求路径:/emps/{ids}

    请求方式:DELETE

    接口描述:该接口用于批量删除员工的数据信息
  • 请求参数
  • 参数格式:路径参数
  • 参数说明:

参数名

类型

示例

是否必须

备注

ids

数组 array

1,2,3

必须

员工的id数组

  • 请求参数样例:
  • /emps/1,2,3
  • 响应数据
  • 参数格式:application/json
  • 参数说明:

参数名

类型

是否必须

备注

code

number

必须

响应码,1 代表成功,0 代表失败

msg

string

非必须

提示信息

data

object

非必须

返回的数据

  • 响应数据样例:
  • {
    "code":1,
    "msg":"success",
    "data":null
    }

3.3.3 思路分析

fig:

接口文档规定:

  • 前端请求路径:/emps/{ids}
  • 前端请求方式:DELETE

问题1:怎么在controller中接收请求路径中的路径参数?

@PathVariable

问题2:如何限定请求方式是delete?

@DeleteMapping

问题3:在Mapper接口中,执行delete操作的SQL语句时,条件中的id值是不确定的是动态的,怎么实现呢?

Mybatis中的动态SQL:foreach

3.3.4 功能开发

通过查看接口文档:删除员工

请求路径:/emps/{ids}

请求方式:DELETE

请求参数:路径参数 {ids}

响应数据:json格式

EmpController

@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {

@Autowired
private EmpService empService;

//批量删除
@DeleteMapping("/{ids}")
public Result delete(@PathVariable List<Integer> ids){
empService.delete(ids);
return Result.success();
}

//条件分页查询
@GetMapping
public Result page(@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer pageSize,
String name, Short gender,
@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {
//记录日志
log.info("分页查询,参数:{},{},{},{},{},{}", page, pageSize,name, gender, begin, end);
//调用业务层分页查询功能
PageBean pageBean = empService.page(page, pageSize, name, gender, begin, end);
//响应
return Result.success(pageBean);
}
}

EmpService

public interface EmpService {

/**
* 批量删除操作
* @param ids id集合
*/
void delete(List<Integer> ids);

//省略...
}

EmpServiceImpl

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
@Autowired
private EmpMapper empMapper;

@Override
public void delete(List<Integer> ids) {
empMapper.delete(ids);
}

//省略...
}

EmpMapper

@Mapper
public interface EmpMapper {
//批量删除
void delete(List<Integer> ids);

//省略...
}

EmpMapper.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.itheima.mapper.EmpMapper">

<!--批量删除员工-->
<select id="delete">
delete from emp where id in
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>

<!-- 省略... -->

</mapper>

3.3.5 功能测试

功能开发完成后,重启项目工程,打开postman,发起DELETE请求:

fig:

控制台SQL语句:

fig:

3.3.6 前后端联调

打开浏览器,测试后端功能接口:

fig:

fig:

fig: