效果展示
业务逻辑描述
本业务逻辑主要是使用SpringBoot从后台查询数据,然后在前台页面进行展示,整个项目为前后端分离
后台代码
由于是定制化查询,Mybatis-plus 框架无法直接进行调用方法查询,所以这里需要在 Mapper.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.*.system.mapper.DMapper">
<!-- 定义select语句 -->
<select id="findDAndCount" resultType="Dment">
select dept.id,
dept.name,
IFNULL((select count(*) from d doc
where doc.depart_id = dept.id and
doc.deleted = 0 group by depart_id),0)
as deptCount from depart dept;
</select>
</mapper>
注意上方 Mapper.xml 中引入了 deptCount 属性,所以需要在Dment的实体类中定义该属性
关于关键字TableField,可以查看Mybatis-plus文档
@ApiModelProperty(value = "分组查询中的部门人数")
//表示在Mysql表中没有定义的,但新引入的属性,所以备注 exist=false
@TableField(exist = false)
private Integer deptCount;
Mapper.java配置
定义Mapper中的方法
public interface DMapper extends BaseMapper<Dment> {
List<Dment>findDAndCount();
}
Service层代码
public interface DService extends IService<Dment> {
List<Dment> findDAndCount();
}
ServiceImp层代码
实现Service代码
@Service
public class DServiceImpl extends ServiceImpl<DMapper, Dment> implements DService {
@Override
public List<Dment> findDAndCount() {
return this.baseMapper.findDAndCount();
}
}
Controller层代码
@Api(value = "部门管理",tags="部门管理接口")
@RestController
@RequestMapping("/dment")
public class DController {
@Autowired
private DService dService;
@ApiOperation(value = "查询部门及人数", notes="从部门表中分组查出用户人数")
@GetMapping("/findDAndCount")
public Result findDAndCount(){
List<Dment> dments = dService.findDAndCount();
if(ds.size()==0){
throw new BusinessException(ResultCode.DEPARTMENT_NOT_EXIST.getCode(),
ResultCode.DEPARTMENT_NOT_EXIST.getMessage());
}
return Result.ok().data("ds",ds);
}
}
前台代码
1 JS代码
新增前端的 dment.js 文件,这个 js 主要处理 DController 中的请求方法
代码如下:
import request from '../utils/request'
/*
后面每次请求都需要携带token
*/
export const findDAndCount = () => {
return request({
url: '/dment/findDAndCount',
method: 'get'
})
}
2 页面详细代码参看点击,这里只记录新增的代码
<!-- template 中的代码 -->
<el-option
v-for="item in ds"
:key="item.id"
:label="item.name"
:value="item.id">
<span style="float: left">{{ item.name }}</span>
<span style="float: right; color: #8492a6; font-size: 13px">
<span class="el-tag el-tag--success el-tag--mini el-tag--plain">{{ item.deptCount }}</span>
</span>
</el-option>
<!-- JS 中代码-->
data(){
/* 即新增 ds 列表 */
return ds: [],
}
methods:{
created () {
// 创建组件的时候,调用部门信息查询
this.getDAndCount();
},
async getDeptAndCount(){
const {data} = await findDAndCount();
// ds 为 Controller中传递的key值
this.ds = data.data.ds;
}
}