Merge branch 'develop' of https://github.com/dibo-software/diboot-v2 into develop

This commit is contained in:
wuy 2019-07-22 22:56:36 +08:00
commit 476250168a
14 changed files with 302 additions and 293 deletions

View File

@ -51,7 +51,7 @@ public class MessageController extends BaseCrudRestController {
* @throws Exception * @throws Exception
*/ */
@GetMapping("/{id}") @GetMapping("/{id}")
public JsonResult getModel(@PathVariable("id")Long id, HttpServletRequest request, ModelMap modelMap) public JsonResult getModel(@PathVariable("id")Long id, HttpServletRequest request)
throws Exception{ throws Exception{
MessageVO entityVO = messageService.getViewObject(id, MessageVO.class); MessageVO entityVO = messageService.getViewObject(id, MessageVO.class);
return new JsonResult(entityVO); return new JsonResult(entityVO);
@ -63,9 +63,9 @@ public class MessageController extends BaseCrudRestController {
* @throws Exception * @throws Exception
*/ */
@PostMapping("/") @PostMapping("/")
public JsonResult createEntity(@ModelAttribute Message entity, BindingResult result, HttpServletRequest request, ModelMap modelMap) public JsonResult createEntity(@ModelAttribute Message entity, BindingResult result, HttpServletRequest request)
throws Exception{ throws Exception{
return super.createEntity(entity, result, modelMap); return super.createEntity(entity, result);
} }
/*** /***
@ -76,8 +76,8 @@ public class MessageController extends BaseCrudRestController {
*/ */
@PutMapping("/{id}") @PutMapping("/{id}")
public JsonResult updateModel(@PathVariable("id")Long id, @ModelAttribute Message entity, BindingResult result, public JsonResult updateModel(@PathVariable("id")Long id, @ModelAttribute Message entity, BindingResult result,
HttpServletRequest request, ModelMap modelMap) throws Exception{ HttpServletRequest request) throws Exception{
return super.updateEntity(entity, result, modelMap); return super.updateEntity(entity, result);
} }
/*** /***

View File

@ -47,7 +47,7 @@ public class MessageTemplateController extends BaseCrudRestController {
* @throws Exception * @throws Exception
*/ */
@GetMapping("/{id}") @GetMapping("/{id}")
public JsonResult getModel(@PathVariable("id")Long id, HttpServletRequest request, ModelMap modelMap) public JsonResult getModel(@PathVariable("id")Long id, HttpServletRequest request)
throws Exception{ throws Exception{
MessageTemplate entity = messageTemplateService.getEntity(id); MessageTemplate entity = messageTemplateService.getEntity(id);
return new JsonResult(entity); return new JsonResult(entity);
@ -59,9 +59,9 @@ public class MessageTemplateController extends BaseCrudRestController {
* @throws Exception * @throws Exception
*/ */
@PostMapping("/") @PostMapping("/")
public JsonResult createEntity(@ModelAttribute MessageTemplate entity, BindingResult result, HttpServletRequest request, ModelMap modelMap) public JsonResult createEntity(@ModelAttribute MessageTemplate entity, BindingResult result, HttpServletRequest request)
throws Exception{ throws Exception{
return super.createEntity(entity, result, modelMap); return super.createEntity(entity, result);
} }
/*** /***
@ -72,8 +72,8 @@ public class MessageTemplateController extends BaseCrudRestController {
*/ */
@PutMapping("/{id}") @PutMapping("/{id}")
public JsonResult updateModel(@PathVariable("id")Long id, @ModelAttribute MessageTemplate entity, BindingResult result, public JsonResult updateModel(@PathVariable("id")Long id, @ModelAttribute MessageTemplate entity, BindingResult result,
HttpServletRequest request, ModelMap modelMap) throws Exception{ HttpServletRequest request) throws Exception{
return super.updateEntity(entity, result, modelMap); return super.updateEntity(entity, result);
} }
/*** /***

View File

@ -1,18 +1,18 @@
## diboot-core: 全新优化内核 # diboot-core: 全新优化内核
主要实现: 主要实现:
1. 多表关联的自动绑定, 实现单表CRUD和多表关联的无SQL化 1. 多表关联的自动绑定, 实现单表CRUD和多表关联的无SQL化
2. 提供其他常用开发场景的最佳实践封装。 2. 提供其他常用开发场景的最佳实践封装。
### ** 单表CRUD无SQL ## ** 一. 单表CRUD无SQL
> 依赖Mybatis-Plus实现Mybatis-Plus具备通用Mapper方案和灵活的查询构造器 > 依赖Mybatis-Plus实现Mybatis-Plus具备通用Mapper方案和灵活的查询构造器
### ** 多表关联查询无SQL适用于大多数场景拆分成单表查询自动实现结果绑定 ## ** 二. 多表关联查询无SQL适用于大多数场景拆分成单表查询自动实现结果绑定
> 通过注解实现多数场景下的关联查询无SQL > 通过注解实现多数场景下的关联查询无SQL
#### 2.1. 注解自动绑定数据字典(枚举)的显示值Label ### 1. 注解自动绑定数据字典(自定义枚举)的显示值Label
~~~java ~~~java
@BindDict(type="GENDER", field = "gender") @BindDict(type="USER_STATUS", field = "status")
private String genderLabel; private String statusLabel;
~~~ ~~~
#### 2. 注解自动绑定其他表的字段 ### 2. 注解自动绑定其他表的字段
~~~java ~~~java
// 支持关联条件+附加条件绑定字段 // 支持关联条件+附加条件绑定字段
@BindField(entity=Department.class, field="name", condition="department_id=id AND parent_id>=0") @BindField(entity=Department.class, field="name", condition="department_id=id AND parent_id>=0")
@ -22,7 +22,7 @@ private String deptName;
@BindField(entity = Organization.class, field="name", condition="this.department_id=department.id AND department.org_id=id") @BindField(entity = Organization.class, field="name", condition="this.department_id=department.id AND department.org_id=id")
private String orgName; private String orgName;
~~~ ~~~
#### 3. 注解自动绑定其他表实体Entity ### 3. 注解自动绑定其他表实体Entity
~~~java ~~~java
// 支持关联条件+附加条件绑定Entity // 支持关联条件+附加条件绑定Entity
@BindEntity(entity = Department.class, condition="department_id=id") @BindEntity(entity = Department.class, condition="department_id=id")
@ -32,7 +32,7 @@ private Department department;
@BindEntity(entity = Organization.class, condition = "this.department_id=department.id AND department.org_id=id AND department.deleted=0") @BindEntity(entity = Organization.class, condition = "this.department_id=department.id AND department.org_id=id AND department.deleted=0")
private Organization organization; private Organization organization;
~~~ ~~~
#### 4. 注解自动绑定其他表实体集合List<Entity> ### 4. 注解自动绑定其他表实体集合List<Entity>
~~~java ~~~java
// 支持关联条件+附加条件绑定多个Entity // 支持关联条件+附加条件绑定多个Entity
@BindEntityList(entity = Department.class, condition = "id=parent_id") @BindEntityList(entity = Department.class, condition = "id=parent_id")
@ -43,21 +43,34 @@ private List<Department> children;
private List<Role> roleList; private List<Role> roleList;
~~~ ~~~
### ** 调用方式 ## ** 三. 使用方式
#### 1. 自动绑定关联(不需要转型) ### 1. 引入依赖
Gradle:
~~~gradle
compile("com.diboot:diboot-core:2.0.1")
~~~
或Maven
~~~xml
<dependency>
<groupId>com.diboot</groupId>
<artifactId>diboot-core</artifactId>
<version>2.0.1</version>
</dependency>
~~~
### 2. 定义你的Service继承diboot的BaseService或Mybatis-plus的ISerivice及Mapper
### 3. 使用注解绑定:
调用RelationsBinder自动绑定注解相关关联
#### 方式1. 自动绑定关联(不需要转型)
~~~java ~~~java
// 调用AnnotationBindingManager自动绑定注解相关关联
//List<MyUserVO> voList = ...; //List<MyUserVO> voList = ...;
RelationsBinder.bind(voList); RelationsBinder.bind(voList);
~~~ ~~~
#### 2. 自动转型并绑定关联(需要转型) #### 方式2. 自动转型并绑定关联(需要转型)
~~~java ~~~java
// 获取Entity列表 // 查询单表获取Entity集合
List<User> entityList = userService.getEntityList(queryWrapper); // List<User> entityList = userService.list(queryWrapper);
// 调用AnnotationBindingManager自动绑定注解相关关联
List<MyUserVO> voList = RelationsBinder.convertAndBind(userList, MyUserVO.class); List<MyUserVO> voList = RelationsBinder.convertAndBind(userList, MyUserVO.class);
~~~ ~~~
## 四. 样例参考 - [diboot-core-example](https://github.com/dibo-software/diboot-v2-example/tree/master/diboot-core-example)
##### 使用样例请参考 - [diboot-core-example](https://github.com/dibo-software/diboot-v2-example/tree/master/diboot-core-example)

View File

@ -27,191 +27,223 @@ import java.util.Map;
*/ */
@RestController @RestController
public abstract class BaseCrudRestController extends BaseController { public abstract class BaseCrudRestController extends BaseController {
private static final Logger log = LoggerFactory.getLogger(BaseCrudRestController.class); private static final Logger log = LoggerFactory.getLogger(BaseCrudRestController.class);
/** /**
* 获取service实例 * 获取service实例
* @return *
*/ * @return
protected abstract BaseService getService(); */
protected abstract BaseService getService();
/*** /***
* 获取某资源的集合 * 获取某资源的集合
* <p> * <p>
* url参数示例: /dictionary/list?_pageSize=20&_pageIndex=1&_orderBy=itemValue&type=GENDAR * url参数示例: /dictionary/list?_pageSize=20&_pageIndex=1&_orderBy=itemValue&type=GENDAR
* </p> * </p>
* @param request * @param request
* @return JsonResult * @return JsonResult
* @throws Exception * @throws Exception
*/ */
protected <T> JsonResult getEntityList(HttpServletRequest request, Wrapper queryWrapper) throws Exception { protected JsonResult getEntityList(HttpServletRequest request, Wrapper queryWrapper) throws Exception {
// 查询当前页的数据 // 查询当前页的数据
List entityList = getService().getEntityList(queryWrapper); List entityList = getService().getEntityList(queryWrapper);
// 返回结果 // 返回结果
return new JsonResult(Status.OK, entityList); return new JsonResult(Status.OK, entityList);
}
/***
* 获取某资源的集合
* <p>
* url参数示例: /dictionary/list?_pageSize=20&_pageIndex=1&_orderBy=itemValue&type=GENDAR
* </p>
* @param request
* @return JsonResult
* @throws Exception
*/
protected JsonResult getEntityListWithPaging(HttpServletRequest request, Wrapper queryWrapper) throws Exception {
// 构建分页
Pagination pagination = buildPagination(request);
// 查询当前页的数据
List entityList = getService().getEntityList(queryWrapper, pagination);
// 返回结果
return new JsonResult(Status.OK, entityList).bindPagination(pagination);
}
/***
* 获取某VO资源的集合
* <p>
* url参数示例: /dictionary/list?_pageSize=20&_pageIndex=1&_orderBy=itemValue&type=GENDAR
* </p>
* @param request
* @return JsonResult
* @throws Exception
*/
protected <T> JsonResult getVOListWithPaging(HttpServletRequest request, Wrapper queryWrapper, Class<T> clazz) throws Exception {
// 构建分页
Pagination pagination = buildPagination(request);
// 查询当前页的数据
List<T> voList = getService().getViewObjectList(queryWrapper, pagination, clazz);
// 返回结果
return new JsonResult(Status.OK, voList).bindPagination(pagination);
}
/***
* 根据id获取某资源对象
* @param id
* @return JsonResult
* @throws Exception
*/
protected JsonResult getEntity(Long id) throws Exception {
Object entity = getService().getEntity(id);
return new JsonResult(Status.OK, entity);
} }
/*** /***
* 创建资源对象 * 获取某资源的集合
* @param entity * <p>
* @param result * url参数示例: /dictionary/list?_pageSize=20&_pageIndex=1&_orderBy=itemValue&type=GENDAR
* @return JsonResult * </p>
* @throws Exception * @param request
*/ * @return JsonResult
protected JsonResult createEntity(BaseEntity entity, BindingResult result, ModelMap modelMap) throws Exception { * @throws Exception
*/
protected JsonResult getEntityListWithPaging(HttpServletRequest request, Wrapper queryWrapper) throws Exception {
// 构建分页
Pagination pagination = buildPagination(request);
// 查询当前页的数据
List entityList = getService().getEntityList(queryWrapper, pagination);
// 返回结果
return new JsonResult(Status.OK, entityList).bindPagination(pagination);
}
/***
* 获取某VO资源的集合
* <p>
* url参数示例: /dictionary/list?_pageSize=20&_pageIndex=1&_orderBy=itemValue&type=GENDAR
* </p>
* @param request
* @return JsonResult
* @throws Exception
*/
protected <T> JsonResult getVOListWithPaging(HttpServletRequest request, Wrapper queryWrapper, Class<T> clazz) throws Exception {
// 构建分页
Pagination pagination = buildPagination(request);
// 查询当前页的数据
List<T> voList = getService().getViewObjectList(queryWrapper, pagination, clazz);
// 返回结果
return new JsonResult(Status.OK, voList).bindPagination(pagination);
}
/***
* 创建资源对象
* @param entity
* @param result
* @return JsonResult
* @throws Exception
*/
protected JsonResult createEntity(BaseEntity entity, BindingResult result) throws Exception {
// Model属性值验证结果 // Model属性值验证结果
if(result != null && result.hasErrors()) { if (result != null && result.hasErrors()) {
return new JsonResult(Status.FAIL_INVALID_PARAM, super.getBindingError(result)); return new JsonResult(Status.FAIL_INVALID_PARAM, super.getBindingError(result));
} }
if(modelMap.get(ERROR) != null){ // 执行创建资源前的操作
return new JsonResult(Status.FAIL_VALIDATION, (String) modelMap.get(ERROR)); String validateResult = this.beforeCreate(entity);
} if (validateResult != null) {
return new JsonResult(Status.FAIL_VALIDATION, validateResult);
}
// 执行保存操作 // 执行保存操作
boolean success = getService().createEntity(entity); boolean success = getService().createEntity(entity);
if(success){ if (success) {
// 组装返回结果 // 执行创建成功后的操作
Map<String, Object> data = new HashMap<>(2); this.afterCreated(entity);
data.put(PARAM_ID, entity.getId()); // 组装返回结果
return new JsonResult(Status.OK, data); Map<String, Object> data = new HashMap<>(2);
} data.put(PARAM_ID, entity.getId());
else{ return new JsonResult(Status.OK, data);
log.warn("创建操作未成功model="+entity.getClass().getSimpleName()); } else {
// 组装返回结果 log.warn("创建操作未成功model=" + entity.getClass().getSimpleName());
return new JsonResult(Status.FAIL_OPERATION); // 组装返回结果
return new JsonResult(Status.FAIL_OPERATION);
} }
} }
/*** /***
* 根据ID更新资源对象 * 根据ID更新资源对象
* @param entity * @param entity
* @param result * @param result
* @return JsonResult * @return JsonResult
* @throws Exception * @throws Exception
*/ */
protected JsonResult updateEntity(BaseEntity entity, BindingResult result, ModelMap modelMap) throws Exception{ protected JsonResult updateEntity(BaseEntity entity, BindingResult result) throws Exception {
// Model属性值验证结果 // Model属性值验证结果
if(result.hasErrors()) { if (result.hasErrors()) {
return new JsonResult(Status.FAIL_INVALID_PARAM, super.getBindingError(result)); return new JsonResult(Status.FAIL_INVALID_PARAM, super.getBindingError(result));
}
if(modelMap.get(ERROR) != null){
return new JsonResult(Status.FAIL_VALIDATION, (String) modelMap.get(ERROR));
}
// 执行保存操作
boolean success = getService().updateEntity(entity);
if(success){
// 组装返回结果
Map<String, Object> data = new HashMap<>(2);
data.put(PARAM_ID, entity.getId());
return new JsonResult(Status.OK, data);
} }
else{ // 执行更新资源前的操作
log.warn("更新操作失败model="+entity.getClass().getSimpleName()+", id="+entity.getId()); String validateResult = this.beforeUpdate(entity);
// 返回操作结果 if (validateResult != null) {
return new JsonResult(Status.FAIL_OPERATION); return new JsonResult(Status.FAIL_VALIDATION, validateResult);
} }
} // 执行保存操作
boolean success = getService().updateEntity(entity);
/*** if (success) {
* 根据id删除资源对象 // 执行更新成功后的操作
* @param id this.afterUpdated(entity);
* @return // 组装返回结果
* @throws Exception Map<String, Object> data = new HashMap<>(2);
*/ data.put(PARAM_ID, entity.getId());
protected JsonResult deleteEntity(Serializable id) throws Exception{ return new JsonResult(Status.OK, data);
if(id == null) { } else {
return new JsonResult(Status.FAIL_INVALID_PARAM, "请选择需要删除的条目!"); log.warn("更新操作失败model=" + entity.getClass().getSimpleName() + ", id=" + entity.getId());
// 返回操作结果
return new JsonResult(Status.FAIL_OPERATION);
} }
// 是否有权限删除 }
BaseEntity model = (BaseEntity) getService().getEntity(id);
// 执行删除操作
String error = beforeDelete(model);
if(error != null){
// 返回json
return new JsonResult(Status.FAIL_OPERATION, error);
}
// 执行删除操作
boolean success = getService().deleteEntity(id);
if(success){
log.info("删除操作成功model="+model.getClass().getSimpleName()+", id="+id);
// 组装返回结果
Map<String, Object> data = new HashMap<>(2);
data.put(PARAM_ID, model.getId());
return new JsonResult(Status.OK, data);
}
else{
log.warn("删除操作未成功model="+model.getClass().getSimpleName()+", id="+id);
return new JsonResult(Status.FAIL_OPERATION);
}
}
/** /***
* 自动转换为VO并绑定关联关系 * 根据id删除资源对象
* @param entityList * @param id
* @param voClass * @return
* @param <VO> * @throws Exception
* @return */
*/ protected JsonResult deleteEntity(Serializable id) throws Exception {
protected <VO> List<VO> convertToVoAndBindRelations(List entityList, Class<VO> voClass){ if (id == null) {
// 转换为VO return new JsonResult(Status.FAIL_INVALID_PARAM, "请选择需要删除的条目!");
List<VO> voList = RelationsBinder.convertAndBind(entityList, voClass); }
return voList; // 是否有权限删除
} BaseEntity model = (BaseEntity) getService().getEntity(id);
// 执行删除操作
String validateResult = beforeDelete(model);
if (validateResult != null) {
// 返回json
return new JsonResult(Status.FAIL_OPERATION, validateResult);
}
// 执行删除操作
boolean success = getService().deleteEntity(id);
if (success) {
log.info("删除操作成功model=" + model.getClass().getSimpleName() + ", id=" + id);
// 组装返回结果
Map<String, Object> data = new HashMap<>(2);
data.put(PARAM_ID, model.getId());
return new JsonResult(Status.OK, data);
} else {
log.warn("删除操作未成功model=" + model.getClass().getSimpleName() + ", id=" + id);
return new JsonResult(Status.FAIL_OPERATION);
}
}
//============= 供子类继承重写的方法 ================= /**
/*** * 自动转换为VO并绑定关联关系
* 是否有删除权限如不可删除返回错误提示信息 Status.FAIL_NO_PERMISSION.label() *
* @param entity * @param entityList
* @return * @param voClass
*/ * @param <VO>
protected String beforeDelete(BaseEntity entity){ * @return
return null; */
} protected <VO> List<VO> convertToVoAndBindRelations(List entityList, Class<VO> voClass) {
// 转换为VO
List<VO> voList = RelationsBinder.convertAndBind(entityList, voClass);
return voList;
}
//============= 供子类继承重写的方法 =================
/***
* 创建前的相关处理
* @param entity
* @return
*/
protected String beforeCreate(BaseEntity entity) throws Exception {
return null;
}
/***
* 创建成功后的相关处理
* @param entity
* @return
*/
protected String afterCreated(BaseEntity entity) throws Exception {
return null;
}
/***
* 更新前的相关处理
* @param entity
* @return
*/
protected String beforeUpdate(BaseEntity entity) throws Exception {
return null;
}
/***
* 更新成功后的相关处理
* @param entity
* @return
*/
protected String afterUpdated(BaseEntity entity) throws Exception {
return null;
}
/***
* 是否有删除权限如不可删除返回错误提示信息 Status.FAIL_NO_PERMISSION.label()
* @param entity
* @return
*/
protected String beforeDelete(BaseEntity entity) {
return null;
}
} }

View File

@ -26,9 +26,6 @@ import java.util.Map;
public class DefaultExceptionHandler { public class DefaultExceptionHandler {
private final static Logger log = LoggerFactory.getLogger(DefaultExceptionHandler.class); private final static Logger log = LoggerFactory.getLogger(DefaultExceptionHandler.class);
@Autowired
private ServerProperties serverProperties;
/** /**
* 统一异常处理类 * 统一异常处理类
* @param request * @param request

View File

@ -15,7 +15,7 @@ public class PropertiesTest {
@Test @Test
public void testGetString(){ public void testGetString(){
String str1 = PropertiesUtils.get("spring.datasource.url"); String str1 = PropertiesUtils.get("spring.datasource.url");
String str2 = PropertiesUtils.get("spring.datasource.url", "application.properties.bak"); String str2 = PropertiesUtils.get("spring.datasource.url", "application.properties");
Assert.assertNotNull(str1); Assert.assertNotNull(str1);
Assert.assertNotNull(str2); Assert.assertNotNull(str2);
} }

View File

@ -36,7 +36,6 @@ import java.util.List;
@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class}) @EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})
@EnableTransactionManagement(proxyTargetClass=true) @EnableTransactionManagement(proxyTargetClass=true)
@ComponentScan(basePackages={"com.diboot"}) @ComponentScan(basePackages={"com.diboot"})
@MapperScan({"com.diboot.**.mapper"})
public class SpringMvcConfig implements WebMvcConfigurer{ public class SpringMvcConfig implements WebMvcConfigurer{
private static final Logger log = LoggerFactory.getLogger(SpringMvcConfig.class); private static final Logger log = LoggerFactory.getLogger(SpringMvcConfig.class);

View File

@ -95,12 +95,12 @@ public class DepartmentController extends BaseCrudRestController {
* @throws Exception * @throws Exception
*/ */
@PostMapping("/") @PostMapping("/")
public JsonResult createEntity(@ModelAttribute DepartmentVO viewObject, BindingResult result, HttpServletRequest request, ModelMap modelMap) public JsonResult createEntity(@ModelAttribute DepartmentVO viewObject, BindingResult result, HttpServletRequest request)
throws Exception{ throws Exception{
// 转换 // 转换
Department entity = BeanUtils.convert(viewObject, Department.class); Department entity = BeanUtils.convert(viewObject, Department.class);
// 创建 // 创建
return super.createEntity(entity, result, modelMap); return super.createEntity(entity, result);
} }
/*** /***
@ -110,7 +110,7 @@ public class DepartmentController extends BaseCrudRestController {
* @throws Exception * @throws Exception
*/ */
@GetMapping("/{id}") @GetMapping("/{id}")
public JsonResult getModel(@PathVariable("id")Long id, HttpServletRequest request, ModelMap modelMap) public JsonResult getModel(@PathVariable("id")Long id, HttpServletRequest request)
throws Exception{ throws Exception{
DepartmentVO vo = departmentService.getViewObject(id, DepartmentVO.class); DepartmentVO vo = departmentService.getViewObject(id, DepartmentVO.class);
return new JsonResult(vo); return new JsonResult(vo);
@ -124,8 +124,8 @@ public class DepartmentController extends BaseCrudRestController {
*/ */
@PutMapping("/{id}") @PutMapping("/{id}")
public JsonResult updateModel(@PathVariable("id")Long id, @ModelAttribute Organization entity, BindingResult result, public JsonResult updateModel(@PathVariable("id")Long id, @ModelAttribute Organization entity, BindingResult result,
HttpServletRequest request, ModelMap modelMap) throws Exception{ HttpServletRequest request) throws Exception{
return super.updateEntity(entity, result, modelMap); return super.updateEntity(entity, result);
} }
/*** /***

View File

@ -1,9 +1,11 @@
package com.diboot.example.controller; package com.diboot.example.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.binding.RelationsBinder; import com.diboot.core.binding.RelationsBinder;
import com.diboot.core.controller.BaseCrudRestController; import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.core.entity.BaseEntity;
import com.diboot.core.service.BaseService; import com.diboot.core.service.BaseService;
import com.diboot.core.service.DictionaryService; import com.diboot.core.service.DictionaryService;
import com.diboot.core.util.V; import com.diboot.core.util.V;
@ -19,6 +21,7 @@ import com.diboot.example.vo.SysUserListVO;
import com.diboot.example.vo.SysUserVO; import com.diboot.example.vo.SysUserVO;
import com.diboot.shiro.entity.Role; import com.diboot.shiro.entity.Role;
import com.diboot.shiro.service.RoleService; import com.diboot.shiro.service.RoleService;
import com.diboot.shiro.util.AuthHelper;
import com.diboot.shiro.util.JwtHelper; import com.diboot.shiro.util.JwtHelper;
import com.diboot.shiro.vo.RoleVO; import com.diboot.shiro.vo.RoleVO;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -62,14 +65,13 @@ public class SysUserController extends BaseCrudRestController {
return new JsonResult(Status.OK, userVoList).bindPagination(pagination); return new JsonResult(Status.OK, userVoList).bindPagination(pagination);
} }
/*** /***
* 创建Entity * 创建Entity
* @return * @return
* @throws Exception * @throws Exception
*/ */
@PostMapping("/") @PostMapping("/")
public JsonResult createEntity(@RequestBody SysUser entity, BindingResult result, HttpServletRequest request, ModelMap modelMap) public JsonResult createEntity(@RequestBody SysUser entity, BindingResult result, HttpServletRequest request)
throws Exception{ throws Exception{
boolean success = sysUserService.createSysUser(entity); boolean success = sysUserService.createSysUser(entity);
if(success){ if(success){
@ -88,21 +90,17 @@ public class SysUserController extends BaseCrudRestController {
*/ */
@PutMapping("/{id}") @PutMapping("/{id}")
public JsonResult updateModel(@PathVariable("id")Long id, @RequestBody SysUser entity, BindingResult result, public JsonResult updateModel(@PathVariable("id")Long id, @RequestBody SysUser entity, BindingResult result,
HttpServletRequest request, ModelMap modelMap) throws Exception{ HttpServletRequest request) throws Exception{
// Model属性值验证结果 // Model属性值验证结果
if(result.hasErrors()) { if(result.hasErrors()) {
return new JsonResult(Status.FAIL_INVALID_PARAM, super.getBindingError(result)); return new JsonResult(Status.FAIL_INVALID_PARAM, super.getBindingError(result));
} }
if(modelMap.get(ERROR) != null){
return new JsonResult(Status.FAIL_VALIDATION, (String) modelMap.get(ERROR));
}
entity.setId(id); entity.setId(id);
boolean success = sysUserService.updateSysUser(entity); boolean success = sysUserService.updateSysUser(entity);
if(success){ if(success){
return new JsonResult(Status.OK); return new JsonResult(Status.OK, "更新成功");
}else{ }else{
return new JsonResult(Status.FAIL_OPERATION); return new JsonResult(Status.FAIL_OPERATION, "更新失败");
} }
} }
@ -113,7 +111,7 @@ public class SysUserController extends BaseCrudRestController {
* @throws Exception * @throws Exception
*/ */
@GetMapping("/{id}") @GetMapping("/{id}")
public JsonResult getModel(@PathVariable("id")Long id, HttpServletRequest request, ModelMap modelMap) public JsonResult getModel(@PathVariable("id")Long id, HttpServletRequest request)
throws Exception{ throws Exception{
SysUserVO sysUserVO = sysUserService.getSysUser(id); SysUserVO sysUserVO = sysUserService.getSysUser(id);
return new JsonResult(sysUserVO); return new JsonResult(sysUserVO);
@ -173,39 +171,24 @@ public class SysUserController extends BaseCrudRestController {
* 校验用户名是否重复 * 校验用户名是否重复
* */ * */
@GetMapping("/checkUsernameRepeat") @GetMapping("/checkUsernameRepeat")
public JsonResult checkUsernameRepeat(@RequestParam("id") Long id,@RequestParam("username") String username, HttpServletRequest request){ public JsonResult checkUsernameRepeat(@RequestParam(required = false) Long id,@RequestParam String username, HttpServletRequest request){
if(V.notEmpty(username)){ if(V.isEmpty(username)){
QueryWrapper<SysUser> wrapper = new QueryWrapper(); return new JsonResult(Status.OK);
wrapper.lambda().eq(SysUser::getUsername, username); }
List<SysUser> sysUserList = sysUserService.getEntityList(wrapper); LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
if(V.isEmpty(id)){//新建时 queryWrapper.eq(SysUser::getUsername, username);
if(V.notEmpty(sysUserList)){ if (id != null){
return new JsonResult(Status.FAIL_OPERATION, "用户名已存在"); queryWrapper.ne(SysUser::getId, id);
}
}else{//更新时
SysUser sysUser = sysUserService.getEntity(id);
if(V.notEmpty(sysUser)){
if(V.notEmpty(sysUserList)){
if(sysUserList.size() >= 2){
return new JsonResult(Status.FAIL_OPERATION, "用户名已存在");
}else if(!(sysUser.getId().equals(sysUserList.get(0).getId()))){
return new JsonResult(Status.FAIL_OPERATION, "用户名已存在");
}
}
}else{
if(V.notEmpty(sysUserList)){
return new JsonResult(Status.FAIL_OPERATION, "用户名已存在");
}
}
}
} }
return new JsonResult(Status.OK); List<SysUser> sysUserList = sysUserService.getEntityList(queryWrapper);
if (V.isEmpty(sysUserList)){
return new JsonResult(Status.OK, "用户名可用");
}
return new JsonResult(Status.FAIL_OPERATION, "用户名已存在");
} }
/*** /***
* 获取登录用户信息 * 获取登录用户信息
* @param request * @param request

View File

@ -1,10 +1,6 @@
package com.diboot.example.entity; package com.diboot.example.entity;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.diboot.core.entity.BaseEntity;
import com.diboot.shiro.entity.Permission;
import com.diboot.shiro.entity.Role;
import com.diboot.shiro.vo.RoleVO;
import lombok.Data; import lombok.Data;
import java.util.List; import java.util.List;
@ -15,7 +11,7 @@ import java.util.List;
* @date 2019/6/6 * @date 2019/6/6
*/ */
@Data @Data
public class SysUser extends BaseEntity { public class SysUser extends com.diboot.shiro.entity.SysUser {
private static final long serialVersionUID = 466801280426981780L; private static final long serialVersionUID = 466801280426981780L;
@ -24,18 +20,6 @@ public class SysUser extends BaseEntity {
// gender字段的关联元数据 // gender字段的关联元数据
public static final String GENDER = "GENDER"; public static final String GENDER = "GENDER";
@TableField
private Long departmentId;
@TableField
private String username;
@TableField
private String password;
@TableField
private String gender;
@TableField @TableField
private String phone; private String phone;
@ -47,13 +31,4 @@ public class SysUser extends BaseEntity {
@TableField @TableField
private String comment; private String comment;
@TableField(exist = false)
private List<Role> roleList;
@TableField(exist = false)
private List<RoleVO> roleVOList;
@TableField(exist = false)
private List<Permission> permissionList;
} }

View File

@ -13,6 +13,7 @@ import com.diboot.example.vo.SysUserVO;
import com.diboot.shiro.entity.Role; import com.diboot.shiro.entity.Role;
import com.diboot.shiro.entity.UserRole; import com.diboot.shiro.entity.UserRole;
import com.diboot.shiro.service.UserRoleService; import com.diboot.shiro.service.UserRoleService;
import com.diboot.shiro.util.AuthHelper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -75,6 +76,11 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser>
@Override @Override
@Transactional @Transactional
public boolean createSysUser(SysUser user) { public boolean createSysUser(SysUser user) {
// 对密码进行处理
if (V.notEmpty(user.getPassword())){
this.encryptPassword(user);
}
//新建用户信息 //新建用户信息
boolean success = super.createEntity(user); boolean success = super.createEntity(user);
if(!success){ if(!success){
@ -102,6 +108,10 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser>
@Override @Override
@Transactional @Transactional
public boolean updateSysUser(SysUser user) { public boolean updateSysUser(SysUser user) {
// 对密码进行处理
if (V.notEmpty(user.getPassword())){
this.encryptPassword(user);
}
//更新用户信息 //更新用户信息
boolean success = super.updateEntity(user); boolean success = super.updateEntity(user);
if(!success){ if(!success){
@ -182,4 +192,15 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser>
return true; return true;
} }
/***
* 设置加密密码相关的数据
* @param sysUser
*/
private void encryptPassword(SysUser sysUser) {
String salt = AuthHelper.createSalt();
String password = AuthHelper.encryptMD5(sysUser.getPassword(), salt, true);
sysUser.setSalt(salt);
sysUser.setPassword(password);
}
} }

View File

@ -47,7 +47,7 @@ public class PermissionController extends BaseCrudRestController {
*/ */
@GetMapping("/{id}") @GetMapping("/{id}")
@AuthorizationWrapper(value = @RequiresPermissions("get"), name = "查看") @AuthorizationWrapper(value = @RequiresPermissions("get"), name = "查看")
public JsonResult getModel(@PathVariable("id")Long id, HttpServletRequest request, ModelMap modelMap) public JsonResult getModel(@PathVariable("id")Long id, HttpServletRequest request)
throws Exception{ throws Exception{
PermissionVO vo = permissionService.getViewObject(id, PermissionVO.class); PermissionVO vo = permissionService.getViewObject(id, PermissionVO.class);
return new JsonResult(vo); return new JsonResult(vo);
@ -82,12 +82,12 @@ public class PermissionController extends BaseCrudRestController {
*/ */
@RequiresPermissions("permission:add") @RequiresPermissions("permission:add")
@PostMapping("/") @PostMapping("/")
public JsonResult createEntity(@ModelAttribute PermissionVO viewObject, BindingResult result, HttpServletRequest request, ModelMap modelMap) public JsonResult createEntity(@ModelAttribute PermissionVO viewObject, BindingResult result, HttpServletRequest request)
throws Exception{ throws Exception{
// 转换 // 转换
Permission entity = BeanUtils.convert(viewObject, Permission.class); Permission entity = BeanUtils.convert(viewObject, Permission.class);
// 创建 // 创建
return super.createEntity(entity, result, modelMap); return super.createEntity(entity, result);
} }
/*** /***
@ -99,8 +99,8 @@ public class PermissionController extends BaseCrudRestController {
@RequiresPermissions("permission:update") @RequiresPermissions("permission:update")
@PutMapping("/{id}") @PutMapping("/{id}")
public JsonResult updateModel(@PathVariable("id")Long id, @ModelAttribute Permission entity, BindingResult result, public JsonResult updateModel(@PathVariable("id")Long id, @ModelAttribute Permission entity, BindingResult result,
HttpServletRequest request, ModelMap modelMap) throws Exception{ HttpServletRequest request) throws Exception{
return super.updateEntity(entity, result, modelMap); return super.updateEntity(entity, result);
} }
/*** /***

View File

@ -71,7 +71,7 @@ public class RoleController extends BaseCrudRestController {
* @throws Exception * @throws Exception
*/ */
@PostMapping("/") @PostMapping("/")
public JsonResult createEntity(@RequestBody Role entity, BindingResult result, HttpServletRequest request, ModelMap modelMap) public JsonResult createEntity(@RequestBody Role entity, BindingResult result, HttpServletRequest request)
throws Exception{ throws Exception{
// 创建 // 创建
boolean success = roleService.createRole(entity); boolean success = roleService.createRole(entity);
@ -88,7 +88,7 @@ public class RoleController extends BaseCrudRestController {
* @throws Exception * @throws Exception
*/ */
@GetMapping("/toUpdatePage/{id}") @GetMapping("/toUpdatePage/{id}")
public JsonResult toUpdatePage(@PathVariable("id")Long id, HttpServletRequest request, ModelMap modelMap) public JsonResult toUpdatePage(@PathVariable("id")Long id, HttpServletRequest request)
throws Exception{ throws Exception{
RoleVO roleVO = roleService.toUpdatePage(id); RoleVO roleVO = roleService.toUpdatePage(id);
return new JsonResult(roleVO); return new JsonResult(roleVO);
@ -103,14 +103,11 @@ public class RoleController extends BaseCrudRestController {
*/ */
@PutMapping("/{id}") @PutMapping("/{id}")
public JsonResult updateModel(@PathVariable("id")Long id, @RequestBody Role entity, BindingResult result, public JsonResult updateModel(@PathVariable("id")Long id, @RequestBody Role entity, BindingResult result,
HttpServletRequest request, ModelMap modelMap) throws Exception{ HttpServletRequest request) throws Exception{
// Model属性值验证结果 // Model属性值验证结果
if(result.hasErrors()) { if(result.hasErrors()) {
return new JsonResult(Status.FAIL_INVALID_PARAM, super.getBindingError(result)); return new JsonResult(Status.FAIL_INVALID_PARAM, super.getBindingError(result));
} }
if(modelMap.get(ERROR) != null){
return new JsonResult(Status.FAIL_VALIDATION, (String) modelMap.get(ERROR));
}
entity.setId(id); entity.setId(id);
boolean success = roleService.updateRole(entity); boolean success = roleService.updateRole(entity);
@ -129,7 +126,7 @@ public class RoleController extends BaseCrudRestController {
* @throws Exception * @throws Exception
*/ */
@GetMapping("/{id}") @GetMapping("/{id}")
public JsonResult getModel(@PathVariable("id")Long id, HttpServletRequest request, ModelMap modelMap) public JsonResult getModel(@PathVariable("id")Long id, HttpServletRequest request)
throws Exception{ throws Exception{
RoleVO roleVO = roleService.getRole(id); RoleVO roleVO = roleService.getRole(id);
return new JsonResult(roleVO); return new JsonResult(roleVO);
@ -157,7 +154,7 @@ public class RoleController extends BaseCrudRestController {
* @throws Exception * @throws Exception
*/ */
@GetMapping("/getAllMenu") @GetMapping("/getAllMenu")
public JsonResult getAllMenu(HttpServletRequest request, ModelMap modelMap) public JsonResult getAllMenu(HttpServletRequest request)
throws Exception{ throws Exception{
List<Permission> list = roleService.getAllMenu(); List<Permission> list = roleService.getAllMenu();
return new JsonResult(list); return new JsonResult(list);

View File

@ -41,12 +41,4 @@ public class SysUser extends BaseEntity {
@TableField(exist = false) @TableField(exist = false)
private List<Permission> permissionList; private List<Permission> permissionList;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
} }