请求参数封装:
cpp
@Data
public class EmployeePageQueryDTO implements Serializable {
//员工姓名
private String name;
//页码
private int page;
//每页显示记录数
private int pageSize;
}
请求结果封装:
cpp
public class PageResult implements Serializable {
private long total; //总记录数
private List records; //当前页数据集合
}
Controller层
cpp
@GetMapping("/page")
@ApiOperation("员工分页查询")
public Result<PageResult> page(EmployeePageQueryDTO employeePageQueryDTO){
log.info("员工分页查询,参数为:{}", employeePageQueryDTO);
PageResult pageResult = employeeService.pageQuery(employeePageQueryDTO);//后续定义
return Result.success(pageResult);
}
Service层
cpp
public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
// select * from employee limit 0,10
//开始分页查询
PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);//后续定义
long total = page.getTotal();
List<Employee> records = page.getResult();
return new PageResult(total, records);
}
Mapper层
cpp
Page<Employee> pageQuery(EmployeePageQueryDTO employeePageQueryDTO);
cpp
在 src/main/resources/mapper/EmployeeMapper.xml 中编写SQL:
cpp
<select id="pageQuery" resultType="com.sky.entity.Employee">
select * from employee
<where>
<if test="name != null and name != ''">
and name like concat('%',#{name},'%')
</if>
</where>
order by create_time desc
</select>
代码完善
时间的格式有问题:
在WebMvcConfiguration中扩展SpringMVC的消息转换器,统一对日期类型进行格式处理
cpp
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
log.info("扩展消息转换器...");
//创建一个消息转换器对象
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
//需要为消息转换器设置一个对象转换器,对象转换器可以将Java对象序列化为json数据
converter.setObjectMapper(new JacksonObjectMapper());
//将自己的消息转化器加入容器中
converters.add(0,converter);
}