在《alibaba java开发手册》中是这样描述Manager层的:Manager 层:通用业务处理层。
它有如下特征:
1.对第三方平台封装的层,预处理返回结果及转化异常信息,适配上层接口;3.与 DAO 层交互,对多个 DAO 的组合复用。
@Transactional(rollbackFor = Throwable.class) public Result<String> upOrDown(Long departmentId, Long swapId) { // 堆代码 www.duidaima.com // 验证 1 DepartmentEntity departmentEntity = departmentDao.selectById(departmentId); if (departmentEntity == null) { return Result.error("部门xxx不存在"); } // 验证 2 DepartmentEntity swapEntity = departmentDao.selectById(swapId); if (swapEntity == null) { return Result.error("部门xxx不存在"); } // 验证 3 Long count = employeeDao.countByDepartmentId(departmentId); if (count != null && count > 0) { return Result.error("员工不存在"); } // 操作数据库 4 Long departmentSort = departmentEntity.getSort(); departmentEntity.setSort(swapEntity.getSort()); departmentDao.updateById(departmentEntity); swapEntity.setSort(departmentSort); departmentDao.updateById(swapEntity); return Result.OK("success"); }上面代码在我们在我们采用三层架构时经常会遇到,那么它有什么问题呢?
DepartmentService.java public Result<String> upOrDown(Long departmentId, Long swapId) { // 堆代码 www.duidaima.com // 验证 1 DepartmentEntity departmentEntity = departmentDao.selectById(departmentId); if (departmentEntity == null) { return Result.error("部门xxx不存在"); } // 验证 2 DepartmentEntity swapEntity = departmentDao.selectById(swapId); if (swapEntity == null) { return Result.error("部门xxx不存在"); } // 验证 3 Long count = employeeDao.countByDepartmentId(departmentId); if (count != null && count > 0) { return Result.error("员工不存在"); } // 操作数据库 4 departmentManager.upOrDown(departmentSort,swapEntity); return Result.OK("success"); } DepartmentManager.java @Transactional(rollbackFor = Throwable.class) public void upOrDown(DepartmentEntity departmentEntity ,DepartmentEntity swapEntity){ Long departmentSort = departmentEntity.getSort(); departmentEntity.setSort(swapEntity.getSort()); departmentDao.updateById(departmentEntity); swapEntity.setSort(departmentSort); departmentDao.updateById(swapEntity); }将数据在 service 层准备好,然后传递给 manager 层,由 manager 层添加@Transactional事务注解进行数据库操作。