冲突解决;

This commit is contained in:
administrator 2020-09-24 18:46:59 +08:00
parent 6f4f2e2049
commit 5b94d2461f
63 changed files with 2697 additions and 5586 deletions

13
pom.xml
View File

@ -30,6 +30,7 @@
<poi.version>3.17</poi.version> <poi.version>3.17</poi.version>
<velocity.version>1.7</velocity.version> <velocity.version>1.7</velocity.version>
<querydsl.version>4.2.1</querydsl.version> <querydsl.version>4.2.1</querydsl.version>
<jaxb.version>2.3.0.1</jaxb.version>
</properties> </properties>
<!-- 依赖声明 --> <!-- 依赖声明 -->
@ -256,6 +257,18 @@
<encoding>${project.build.sourceEncoding}</encoding> <encoding>${project.build.sourceEncoding}</encoding>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<fork>true</fork>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>

View File

@ -90,6 +90,36 @@
<artifactId>jackson-datatype-hibernate5</artifactId> <artifactId>jackson-datatype-hibernate5</artifactId>
<version>2.10.1</version> <version>2.10.1</version>
</dependency> </dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>${jaxb.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>${jaxb.version}</version>
</dependency>
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -0,0 +1,35 @@
package com.ruoyi.logger;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.util.EnvUtil;
import ch.qos.logback.core.util.OptionHelper;
import java.io.OutputStream;
public class MyConsoleAppender extends ConsoleAppender {
private final static String WindowsAnsiOutputStream_CLASS_NAME = "org.fusesource.jansi.WindowsAnsiPrintStream";
@Override
public void start() {
OutputStream targetStream = target.getStream();
// enable jansi only on Windows and only if withJansi set to true
if (EnvUtil.isWindows() && withJansi) {
targetStream = getTargetStreamForWindows(targetStream);
}
setOutputStream(targetStream);
super.start();
}
private OutputStream getTargetStreamForWindows(OutputStream targetStream) {
try {
addInfo("Enabling JANSI WindowsAnsiOutputStream for the console.");
Object windowsAnsiOutputStream = OptionHelper.instantiateByClassNameAndParameter(WindowsAnsiOutputStream_CLASS_NAME, Object.class, context,
OutputStream.class, targetStream);
return (OutputStream) windowsAnsiOutputStream;
} catch (Exception e) {
addWarn("Failed to create WindowsAnsiOutputStream. Falling back on the default stream.", e);
}
return targetStream;
}
}

View File

@ -1,16 +1,5 @@
package com.ruoyi.web.controller.system; package com.ruoyi.web.controller.system;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log; import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.controller.BaseController;
@ -21,6 +10,15 @@ import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysConfig; import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysConfigService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/** /**
* 参数配置 信息操作处理 * 参数配置 信息操作处理
@ -29,8 +27,7 @@ import com.ruoyi.system.service.ISysConfigService;
*/ */
@Controller @Controller
@RequestMapping("/system/config") @RequestMapping("/system/config")
public class SysConfigController extends BaseController public class SysConfigController extends BaseController {
{
private String prefix = "system/config"; private String prefix = "system/config";
@Autowired @Autowired
@ -38,8 +35,7 @@ public class SysConfigController extends BaseController
@RequiresPermissions("system:config:view") @RequiresPermissions("system:config:view")
@GetMapping() @GetMapping()
public String config() public String config() {
{
return prefix + "/config"; return prefix + "/config";
} }
@ -49,20 +45,16 @@ public class SysConfigController extends BaseController
@RequiresPermissions("system:config:list") @RequiresPermissions("system:config:list")
@PostMapping("/list") @PostMapping("/list")
@ResponseBody @ResponseBody
public TableDataInfo list(SysConfig config) public TableDataInfo list(SysConfig config) {
{ return getDataTable(configService.selectConfigList(config, getPageRequest()));
startPage();
List<SysConfig> list = configService.selectConfigList(config);
return getDataTable(list);
} }
@Log(title = "参数管理", businessType = BusinessType.EXPORT) @Log(title = "参数管理", businessType = BusinessType.EXPORT)
@RequiresPermissions("system:config:export") @RequiresPermissions("system:config:export")
@PostMapping("/export") @PostMapping("/export")
@ResponseBody @ResponseBody
public AjaxResult export(SysConfig config) public AjaxResult export(SysConfig config) {
{ List<SysConfig> list = configService.selectConfigList(config, Pageable.unpaged()).getContent();
List<SysConfig> list = configService.selectConfigList(config);
ExcelUtil<SysConfig> util = new ExcelUtil<SysConfig>(SysConfig.class); ExcelUtil<SysConfig> util = new ExcelUtil<SysConfig>(SysConfig.class);
return util.exportExcel(list, "参数数据"); return util.exportExcel(list, "参数数据");
} }
@ -71,8 +63,7 @@ public class SysConfigController extends BaseController
* 新增参数配置 * 新增参数配置
*/ */
@GetMapping("/add") @GetMapping("/add")
public String add() public String add() {
{
return prefix + "/add"; return prefix + "/add";
} }
@ -83,10 +74,8 @@ public class SysConfigController extends BaseController
@Log(title = "参数管理", businessType = BusinessType.INSERT) @Log(title = "参数管理", businessType = BusinessType.INSERT)
@PostMapping("/add") @PostMapping("/add")
@ResponseBody @ResponseBody
public AjaxResult addSave(@Validated SysConfig config) public AjaxResult addSave(@Validated SysConfig config) {
{ if (UserConstants.CONFIG_KEY_NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) {
if (UserConstants.CONFIG_KEY_NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config)))
{
return error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在"); return error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在");
} }
config.setCreateBy(ShiroUtils.getLoginName()); config.setCreateBy(ShiroUtils.getLoginName());
@ -97,8 +86,7 @@ public class SysConfigController extends BaseController
* 修改参数配置 * 修改参数配置
*/ */
@GetMapping("/edit/{configId}") @GetMapping("/edit/{configId}")
public String edit(@PathVariable("configId") Long configId, ModelMap mmap) public String edit(@PathVariable("configId") Long configId, ModelMap mmap) {
{
mmap.put("config", configService.selectConfigById(configId)); mmap.put("config", configService.selectConfigById(configId));
return prefix + "/edit"; return prefix + "/edit";
} }
@ -110,10 +98,8 @@ public class SysConfigController extends BaseController
@Log(title = "参数管理", businessType = BusinessType.UPDATE) @Log(title = "参数管理", businessType = BusinessType.UPDATE)
@PostMapping("/edit") @PostMapping("/edit")
@ResponseBody @ResponseBody
public AjaxResult editSave(@Validated SysConfig config) public AjaxResult editSave(@Validated SysConfig config) {
{ if (UserConstants.CONFIG_KEY_NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) {
if (UserConstants.CONFIG_KEY_NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config)))
{
return error("修改参数'" + config.getConfigName() + "'失败,参数键名已存在"); return error("修改参数'" + config.getConfigName() + "'失败,参数键名已存在");
} }
config.setUpdateBy(ShiroUtils.getLoginName()); config.setUpdateBy(ShiroUtils.getLoginName());
@ -127,11 +113,19 @@ public class SysConfigController extends BaseController
@Log(title = "参数管理", businessType = BusinessType.DELETE) @Log(title = "参数管理", businessType = BusinessType.DELETE)
@PostMapping("/remove") @PostMapping("/remove")
@ResponseBody @ResponseBody
public AjaxResult remove(String ids) public AjaxResult remove(String ids) {
{
return toAjax(configService.deleteConfigByIds(ids)); return toAjax(configService.deleteConfigByIds(ids));
} }
/**
* 校验参数键名
*/
@PostMapping("/checkConfigKeyUnique")
@ResponseBody
public String checkConfigKeyUnique(SysConfig config) {
return configService.checkConfigKeyUnique(config);
}
/** /**
* 清空缓存 * 清空缓存
*/ */
@ -144,14 +138,4 @@ public class SysConfigController extends BaseController
configService.clearCache(); configService.clearCache();
return success(); return success();
} }
/**
* 校验参数键名
*/
@PostMapping("/checkConfigKeyUnique")
@ResponseBody
public String checkConfigKeyUnique(SysConfig config)
{
return configService.checkConfigKeyUnique(config);
}
} }

View File

@ -1,16 +1,5 @@
package com.ruoyi.web.controller.system; package com.ruoyi.web.controller.system;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log; import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.controller.BaseController;
@ -22,6 +11,15 @@ import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.service.ISysDeptService; import com.ruoyi.system.service.ISysDeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/** /**
* 部门信息 * 部门信息
@ -30,8 +28,7 @@ import com.ruoyi.system.service.ISysDeptService;
*/ */
@Controller @Controller
@RequestMapping("/system/dept") @RequestMapping("/system/dept")
public class SysDeptController extends BaseController public class SysDeptController extends BaseController {
{
private String prefix = "system/dept"; private String prefix = "system/dept";
@Autowired @Autowired
@ -39,26 +36,22 @@ public class SysDeptController extends BaseController
@RequiresPermissions("system:dept:view") @RequiresPermissions("system:dept:view")
@GetMapping() @GetMapping()
public String dept() public String dept() {
{
return prefix + "/dept"; return prefix + "/dept";
} }
@RequiresPermissions("system:dept:list") @RequiresPermissions("system:dept:list")
@PostMapping("/list") @PostMapping("/list")
@ResponseBody @ResponseBody
public List<SysDept> list(SysDept dept) public List<SysDept> list(SysDept dept) {
{ return deptService.selectDeptList(dept, Pageable.unpaged()).getContent();
List<SysDept> deptList = deptService.selectDeptList(dept);
return deptList;
} }
/** /**
* 新增部门 * 新增部门
*/ */
@GetMapping("/add/{parentId}") @GetMapping("/add/{parentId}")
public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) {
{
mmap.put("dept", deptService.selectDeptById(parentId)); mmap.put("dept", deptService.selectDeptById(parentId));
return prefix + "/add"; return prefix + "/add";
} }
@ -70,27 +63,20 @@ public class SysDeptController extends BaseController
@RequiresPermissions("system:dept:add") @RequiresPermissions("system:dept:add")
@PostMapping("/add") @PostMapping("/add")
@ResponseBody @ResponseBody
public AjaxResult addSave(@Validated SysDept dept) public AjaxResult addSave(@Validated SysDept dept) {
{ if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
{
return error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在"); return error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在");
} }
dept.setCreateBy(ShiroUtils.getLoginName()); dept.setCreateBy(ShiroUtils.getLoginName());
return toAjax(deptService.insertDept(dept)); return success(deptService.insertDept(dept));
} }
/** /**
* 修改 * 修改
*/ */
@GetMapping("/edit/{deptId}") @GetMapping("/edit/{deptId}")
public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap) public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap) {
{
SysDept dept = deptService.selectDeptById(deptId); SysDept dept = deptService.selectDeptById(deptId);
if (StringUtils.isNotNull(dept) && 100L == deptId)
{
dept.setParentName("");
}
mmap.put("dept", dept); mmap.put("dept", dept);
return prefix + "/edit"; return prefix + "/edit";
} }
@ -102,23 +88,18 @@ public class SysDeptController extends BaseController
@RequiresPermissions("system:dept:edit") @RequiresPermissions("system:dept:edit")
@PostMapping("/edit") @PostMapping("/edit")
@ResponseBody @ResponseBody
public AjaxResult editSave(@Validated SysDept dept) public AjaxResult editSave(@Validated SysDept dept) {
{ if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
{
return error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在"); return error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在");
} } else if (dept.getParentId().equals(dept.getDeptId())) {
else if (dept.getParentId().equals(dept.getDeptId()))
{
return error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己"); return error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己");
} }else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.countChildren(dept.getDeptId()) > 0){
&& deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0)
{
return AjaxResult.error("该部门包含未停用的子部门!"); return AjaxResult.error("该部门包含未停用的子部门!");
} }
dept.setUpdateBy(ShiroUtils.getLoginName()); dept.setUpdateBy(ShiroUtils.getLoginName());
return toAjax(deptService.updateDept(dept)); deptService.updateDept(dept);
return success();
} }
/** /**
@ -128,17 +109,15 @@ public class SysDeptController extends BaseController
@RequiresPermissions("system:dept:remove") @RequiresPermissions("system:dept:remove")
@GetMapping("/remove/{deptId}") @GetMapping("/remove/{deptId}")
@ResponseBody @ResponseBody
public AjaxResult remove(@PathVariable("deptId") Long deptId) public AjaxResult remove(@PathVariable("deptId") Long deptId) {
{ if (deptService.countChildren(deptId) > 0) {
if (deptService.selectDeptCount(deptId) > 0)
{
return AjaxResult.warn("存在下级部门,不允许删除"); return AjaxResult.warn("存在下级部门,不允许删除");
} }
if (deptService.checkDeptExistUser(deptId)) if (deptService.checkDeptExistUser(deptId)) {
{
return AjaxResult.warn("部门存在用户,不允许删除"); return AjaxResult.warn("部门存在用户,不允许删除");
} }
return toAjax(deptService.deleteDeptById(deptId)); deptService.deleteDeptById(deptId);
return success();
} }
/** /**
@ -146,8 +125,7 @@ public class SysDeptController extends BaseController
*/ */
@PostMapping("/checkDeptNameUnique") @PostMapping("/checkDeptNameUnique")
@ResponseBody @ResponseBody
public String checkDeptNameUnique(SysDept dept) public String checkDeptNameUnique(SysDept dept) {
{
return deptService.checkDeptNameUnique(dept); return deptService.checkDeptNameUnique(dept);
} }
@ -159,7 +137,7 @@ public class SysDeptController extends BaseController
*/ */
@GetMapping(value = { "/selectDeptTree/{deptId}", "/selectDeptTree/{deptId}/{excludeId}" }) @GetMapping(value = { "/selectDeptTree/{deptId}", "/selectDeptTree/{deptId}/{excludeId}" })
public String selectDeptTree(@PathVariable("deptId") Long deptId, public String selectDeptTree(@PathVariable("deptId") Long deptId,
@PathVariable(value = "excludeId", required = false) String excludeId, ModelMap mmap) @PathVariable(value = "excludeId", required = false) String excludeId, ModelMap mmap)
{ {
mmap.put("dept", deptService.selectDeptById(deptId)); mmap.put("dept", deptService.selectDeptById(deptId));
mmap.put("excludeId", excludeId); mmap.put("excludeId", excludeId);
@ -171,32 +149,17 @@ public class SysDeptController extends BaseController
*/ */
@GetMapping("/treeData") @GetMapping("/treeData")
@ResponseBody @ResponseBody
public List<Ztree> treeData() public List<Ztree> treeData() {
{
List<Ztree> ztrees = deptService.selectDeptTree(new SysDept()); List<Ztree> ztrees = deptService.selectDeptTree(new SysDept());
return ztrees; return ztrees;
} }
/**
* 加载部门列表树排除下级
*/
@GetMapping("/treeData/{excludeId}")
@ResponseBody
public List<Ztree> treeDataExcludeChild(@PathVariable(value = "excludeId", required = false) Long excludeId)
{
SysDept dept = new SysDept();
dept.setDeptId(excludeId);
List<Ztree> ztrees = deptService.selectDeptTreeExcludeChild(dept);
return ztrees;
}
/** /**
* 加载角色部门数据权限列表树 * 加载角色部门数据权限列表树
*/ */
@GetMapping("/roleDeptTreeData") @GetMapping("/roleDeptTreeData")
@ResponseBody @ResponseBody
public List<Ztree> deptTreeData(SysRole role) public List<Ztree> deptTreeData(SysRole role) {
{
List<Ztree> ztrees = deptService.roleDeptTreeData(role); List<Ztree> ztrees = deptService.roleDeptTreeData(role);
return ztrees; return ztrees;
} }

View File

@ -1,16 +1,5 @@
package com.ruoyi.web.controller.system; package com.ruoyi.web.controller.system;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log; import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.controller.BaseController;
@ -22,6 +11,15 @@ import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysDictType; import com.ruoyi.system.domain.SysDictType;
import com.ruoyi.system.service.ISysDictTypeService; import com.ruoyi.system.service.ISysDictTypeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/** /**
* 数据字典信息 * 数据字典信息
@ -30,8 +28,7 @@ import com.ruoyi.system.service.ISysDictTypeService;
*/ */
@Controller @Controller
@RequestMapping("/system/dict") @RequestMapping("/system/dict")
public class SysDictTypeController extends BaseController public class SysDictTypeController extends BaseController {
{
private String prefix = "system/dict/type"; private String prefix = "system/dict/type";
@Autowired @Autowired
@ -39,29 +36,23 @@ public class SysDictTypeController extends BaseController
@RequiresPermissions("system:dict:view") @RequiresPermissions("system:dict:view")
@GetMapping() @GetMapping()
public String dictType() public String dictType() {
{
return prefix + "/type"; return prefix + "/type";
} }
@PostMapping("/list") @PostMapping("/list")
@RequiresPermissions("system:dict:list") @RequiresPermissions("system:dict:list")
@ResponseBody @ResponseBody
public TableDataInfo list(SysDictType dictType) public TableDataInfo list(SysDictType dictType) {
{ return getDataTable(dictTypeService.selectDictTypeList(dictType, getPageRequest()));
startPage();
List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
return getDataTable(list);
} }
@Log(title = "字典类型", businessType = BusinessType.EXPORT) @Log(title = "字典类型", businessType = BusinessType.EXPORT)
@RequiresPermissions("system:dict:export") @RequiresPermissions("system:dict:export")
@PostMapping("/export") @PostMapping("/export")
@ResponseBody @ResponseBody
public AjaxResult export(SysDictType dictType) public AjaxResult export(SysDictType dictType) {
{ List<SysDictType> list = dictTypeService.selectDictTypeList(dictType, Pageable.unpaged()).getContent();
List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
ExcelUtil<SysDictType> util = new ExcelUtil<SysDictType>(SysDictType.class); ExcelUtil<SysDictType> util = new ExcelUtil<SysDictType>(SysDictType.class);
return util.exportExcel(list, "字典类型"); return util.exportExcel(list, "字典类型");
} }
@ -70,8 +61,7 @@ public class SysDictTypeController extends BaseController
* 新增字典类型 * 新增字典类型
*/ */
@GetMapping("/add") @GetMapping("/add")
public String add() public String add() {
{
return prefix + "/add"; return prefix + "/add";
} }
@ -82,10 +72,8 @@ public class SysDictTypeController extends BaseController
@RequiresPermissions("system:dict:add") @RequiresPermissions("system:dict:add")
@PostMapping("/add") @PostMapping("/add")
@ResponseBody @ResponseBody
public AjaxResult addSave(@Validated SysDictType dict) public AjaxResult addSave(@Validated SysDictType dict) {
{ if (UserConstants.DICT_TYPE_NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) {
if (UserConstants.DICT_TYPE_NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict)))
{
return error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在"); return error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在");
} }
dict.setCreateBy(ShiroUtils.getLoginName()); dict.setCreateBy(ShiroUtils.getLoginName());
@ -96,8 +84,7 @@ public class SysDictTypeController extends BaseController
* 修改字典类型 * 修改字典类型
*/ */
@GetMapping("/edit/{dictId}") @GetMapping("/edit/{dictId}")
public String edit(@PathVariable("dictId") Long dictId, ModelMap mmap) public String edit(@PathVariable("dictId") Long dictId, ModelMap mmap) {
{
mmap.put("dict", dictTypeService.selectDictTypeById(dictId)); mmap.put("dict", dictTypeService.selectDictTypeById(dictId));
return prefix + "/edit"; return prefix + "/edit";
} }
@ -109,10 +96,8 @@ public class SysDictTypeController extends BaseController
@RequiresPermissions("system:dict:edit") @RequiresPermissions("system:dict:edit")
@PostMapping("/edit") @PostMapping("/edit")
@ResponseBody @ResponseBody
public AjaxResult editSave(@Validated SysDictType dict) public AjaxResult editSave(@Validated SysDictType dict) {
{ if (UserConstants.DICT_TYPE_NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) {
if (UserConstants.DICT_TYPE_NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict)))
{
return error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在"); return error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在");
} }
dict.setUpdateBy(ShiroUtils.getLoginName()); dict.setUpdateBy(ShiroUtils.getLoginName());
@ -123,9 +108,53 @@ public class SysDictTypeController extends BaseController
@RequiresPermissions("system:dict:remove") @RequiresPermissions("system:dict:remove")
@PostMapping("/remove") @PostMapping("/remove")
@ResponseBody @ResponseBody
public AjaxResult remove(String ids) public AjaxResult remove(String ids) {
{ try {
return toAjax(dictTypeService.deleteDictTypeByIds(ids)); return toAjax(dictTypeService.deleteDictTypeByIds(ids));
} catch (Exception e) {
return error(e.getMessage());
}
}
/**
* 查询字典详细
*/
@RequiresPermissions("system:dict:list")
@GetMapping("/detail/{dictId}")
public String detail(@PathVariable("dictId") Long dictId, ModelMap mmap) {
mmap.put("dict", dictTypeService.selectDictTypeById(dictId));
mmap.put("dictList", dictTypeService.selectDictTypeAll());
return "system/dict/data/data";
}
/**
* 校验字典类型
*/
@PostMapping("/checkDictTypeUnique")
@ResponseBody
public String checkDictTypeUnique(SysDictType dictType) {
return dictTypeService.checkDictTypeUnique(dictType);
}
/**
* 选择字典树
*/
@GetMapping("/selectDictTree/{columnId}/{dictType}")
public String selectDeptTree(@PathVariable("columnId") Long columnId, @PathVariable("dictType") String dictType,
ModelMap mmap) {
mmap.put("columnId", columnId);
mmap.put("dict", dictTypeService.selectDictTypeByType(dictType));
return prefix + "/tree";
}
/**
* 加载字典列表树
*/
@GetMapping("/treeData")
@ResponseBody
public List<Ztree> treeData() {
List<Ztree> ztrees = dictTypeService.selectDictTree(new SysDictType());
return ztrees;
} }
/** /**
@ -140,49 +169,4 @@ public class SysDictTypeController extends BaseController
dictTypeService.clearCache(); dictTypeService.clearCache();
return success(); return success();
} }
/**
* 查询字典详细
*/
@RequiresPermissions("system:dict:list")
@GetMapping("/detail/{dictId}")
public String detail(@PathVariable("dictId") Long dictId, ModelMap mmap)
{
mmap.put("dict", dictTypeService.selectDictTypeById(dictId));
mmap.put("dictList", dictTypeService.selectDictTypeAll());
return "system/dict/data/data";
}
/**
* 校验字典类型
*/
@PostMapping("/checkDictTypeUnique")
@ResponseBody
public String checkDictTypeUnique(SysDictType dictType)
{
return dictTypeService.checkDictTypeUnique(dictType);
}
/**
* 选择字典树
*/
@GetMapping("/selectDictTree/{columnId}/{dictType}")
public String selectDeptTree(@PathVariable("columnId") Long columnId, @PathVariable("dictType") String dictType,
ModelMap mmap)
{
mmap.put("columnId", columnId);
mmap.put("dict", dictTypeService.selectDictTypeByType(dictType));
return prefix + "/tree";
}
/**
* 加载字典列表树
*/
@GetMapping("/treeData")
@ResponseBody
public List<Ztree> treeData()
{
List<Ztree> ztrees = dictTypeService.selectDictTree(new SysDictType());
return ztrees;
}
} }

View File

@ -1,22 +1,10 @@
package com.ruoyi.web.controller.system; package com.ruoyi.web.controller.system;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log; import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.common.utils.poi.ExcelUtil;
@ -24,9 +12,22 @@ import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysPostService; import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService; import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService; import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Set;
/** /**
* 用户信息 * 用户信息
@ -35,8 +36,7 @@ import com.ruoyi.system.service.ISysUserService;
*/ */
@Controller @Controller
@RequestMapping("/system/user") @RequestMapping("/system/user")
public class SysUserController extends BaseController public class SysUserController extends BaseController {
{
private String prefix = "system/user"; private String prefix = "system/user";
@Autowired @Autowired
@ -53,38 +53,32 @@ public class SysUserController extends BaseController
@RequiresPermissions("system:user:view") @RequiresPermissions("system:user:view")
@GetMapping() @GetMapping()
public String user() public String user() {
{
return prefix + "/user"; return prefix + "/user";
} }
@RequiresPermissions("system:user:list") @RequiresPermissions("system:user:list")
@PostMapping("/list") @PostMapping("/list")
@ResponseBody @ResponseBody
public TableDataInfo list(SysUser user) public TableDataInfo list(SysUser user) {
{ return getDataTable(userService.selectUserList(user, getPageRequest()));
startPage();
List<SysUser> list = userService.selectUserList(user);
return getDataTable(list);
} }
@Log(title = "用户管理", businessType = BusinessType.EXPORT) @Log(title = "用户管理", businessType = BusinessType.EXPORT)
@RequiresPermissions("system:user:export") @RequiresPermissions("system:user:export")
@PostMapping("/export") @PostMapping("/export")
@ResponseBody @ResponseBody
public AjaxResult export(SysUser user) public AjaxResult export(SysUser user) {
{ Page<SysUser> page = userService.selectUserList(user, Pageable.unpaged());
List<SysUser> list = userService.selectUserList(user);
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class); ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
return util.exportExcel(list, "用户数据"); return util.exportExcel(page.getContent(), "用户数据");
} }
@Log(title = "用户管理", businessType = BusinessType.IMPORT) @Log(title = "用户管理", businessType = BusinessType.IMPORT)
@RequiresPermissions("system:user:import") @RequiresPermissions("system:user:import")
@PostMapping("/importData") @PostMapping("/importData")
@ResponseBody @ResponseBody
public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
{
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class); ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
List<SysUser> userList = util.importExcel(file.getInputStream()); List<SysUser> userList = util.importExcel(file.getInputStream());
String operName = ShiroUtils.getSysUser().getLoginName(); String operName = ShiroUtils.getSysUser().getLoginName();
@ -95,8 +89,7 @@ public class SysUserController extends BaseController
@RequiresPermissions("system:user:view") @RequiresPermissions("system:user:view")
@GetMapping("/importTemplate") @GetMapping("/importTemplate")
@ResponseBody @ResponseBody
public AjaxResult importTemplate() public AjaxResult importTemplate() {
{
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class); ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
return util.importTemplateExcel("用户数据"); return util.importTemplateExcel("用户数据");
} }
@ -105,9 +98,8 @@ public class SysUserController extends BaseController
* 新增用户 * 新增用户
*/ */
@GetMapping("/add") @GetMapping("/add")
public String add(ModelMap mmap) public String add(ModelMap mmap) {
{ mmap.put("roles", roleService.selectRoleAll());
mmap.put("roles", roleService.selectRoleAll().stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
mmap.put("posts", postService.selectPostAll()); mmap.put("posts", postService.selectPostAll());
return prefix + "/add"; return prefix + "/add";
} }
@ -119,36 +111,28 @@ public class SysUserController extends BaseController
@Log(title = "用户管理", businessType = BusinessType.INSERT) @Log(title = "用户管理", businessType = BusinessType.INSERT)
@PostMapping("/add") @PostMapping("/add")
@ResponseBody @ResponseBody
public AjaxResult addSave(@Validated SysUser user) public AjaxResult addSave(@Validated SysUser user) {
{ if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName())))
{
return error("新增用户'" + user.getLoginName() + "'失败,登录账号已存在"); return error("新增用户'" + user.getLoginName() + "'失败,登录账号已存在");
} } else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
{
return error("新增用户'" + user.getLoginName() + "'失败,手机号码已存在"); return error("新增用户'" + user.getLoginName() + "'失败,手机号码已存在");
} } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
{
return error("新增用户'" + user.getLoginName() + "'失败,邮箱账号已存在"); return error("新增用户'" + user.getLoginName() + "'失败,邮箱账号已存在");
} }
user.setSalt(ShiroUtils.randomSalt()); user.setSalt(ShiroUtils.randomSalt());
user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt())); user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
user.setCreateBy(ShiroUtils.getLoginName()); user.setCreateBy(ShiroUtils.getLoginName());
return toAjax(userService.insertUser(user)); return success(userService.insertUser(user));
} }
/** /**
* 修改用户 * 修改用户
*/ */
@GetMapping("/edit/{userId}") @GetMapping("/edit/{userId}")
public String edit(@PathVariable("userId") Long userId, ModelMap mmap) public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
{ mmap.put("user", userService.selectUserWithRolesAndPostsById(userId));
List<SysRole> roles = roleService.selectRolesByUserId(userId); mmap.put("roles", roleService.selectRoleAll());
mmap.put("user", userService.selectUserById(userId)); mmap.put("posts", postService.selectPostAll());
mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
mmap.put("posts", postService.selectPostsByUserId(userId));
return prefix + "/edit"; return prefix + "/edit";
} }
@ -159,25 +143,22 @@ public class SysUserController extends BaseController
@Log(title = "用户管理", businessType = BusinessType.UPDATE) @Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PostMapping("/edit") @PostMapping("/edit")
@ResponseBody @ResponseBody
public AjaxResult editSave(@Validated SysUser user) public AjaxResult editSave(@Validated SysUser user) {
{
userService.checkUserAllowed(user); userService.checkUserAllowed(user);
if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
{
return error("修改用户'" + user.getLoginName() + "'失败,手机号码已存在"); return error("修改用户'" + user.getLoginName() + "'失败,手机号码已存在");
} } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
{
return error("修改用户'" + user.getLoginName() + "'失败,邮箱账号已存在"); return error("修改用户'" + user.getLoginName() + "'失败,邮箱账号已存在");
} }
user.setUpdateBy(ShiroUtils.getLoginName()); user.setUpdateBy(ShiroUtils.getLoginName());
return toAjax(userService.updateUser(user)); userService.updateUser(user);
return success();
} }
@RequiresPermissions("system:user:resetPwd") @RequiresPermissions("system:user:resetPwd")
@Log(title = "重置密码", businessType = BusinessType.UPDATE)
@GetMapping("/resetPwd/{userId}") @GetMapping("/resetPwd/{userId}")
public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) {
{
mmap.put("user", userService.selectUserById(userId)); mmap.put("user", userService.selectUserById(userId));
return prefix + "/resetPwd"; return prefix + "/resetPwd";
} }
@ -186,20 +167,67 @@ public class SysUserController extends BaseController
@Log(title = "重置密码", businessType = BusinessType.UPDATE) @Log(title = "重置密码", businessType = BusinessType.UPDATE)
@PostMapping("/resetPwd") @PostMapping("/resetPwd")
@ResponseBody @ResponseBody
public AjaxResult resetPwdSave(SysUser user) public AjaxResult resetPwdSave(SysUser user) {
{
userService.checkUserAllowed(user); userService.checkUserAllowed(user);
user.setSalt(ShiroUtils.randomSalt()); user.setSalt(ShiroUtils.randomSalt());
user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt())); user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
if (userService.resetUserPwd(user) > 0) userService.resetUserPwd(user);
{ if (ShiroUtils.getUserId() == user.getUserId()) {
if (ShiroUtils.getUserId().longValue() == user.getUserId().longValue()) ShiroUtils.setSysUser(userService.selectUserById(user.getUserId()));
{
ShiroUtils.setSysUser(userService.selectUserById(user.getUserId()));
}
return success();
} }
return error(); return success();
}
@RequiresPermissions("system:user:remove")
@Log(title = "用户管理", businessType = BusinessType.DELETE)
@PostMapping("/remove")
@ResponseBody
public AjaxResult remove(String ids) {
try {
return toAjax(userService.deleteUserByIds(ids));
} catch (Exception e) {
return error(e.getMessage());
}
}
/**
* 校验用户名
*/
@PostMapping("/checkLoginNameUnique")
@ResponseBody
public String checkLoginNameUnique(SysUser user) {
return userService.checkLoginNameUnique(user.getLoginName());
}
/**
* 校验手机号码
*/
@PostMapping("/checkPhoneUnique")
@ResponseBody
public String checkPhoneUnique(SysUser user) {
return userService.checkPhoneUnique(user);
}
/**
* 校验email邮箱
*/
@PostMapping("/checkEmailUnique")
@ResponseBody
public String checkEmailUnique(SysUser user) {
return userService.checkEmailUnique(user);
}
/**
* 用户状态修改
*/
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@RequiresPermissions("system:user:edit")
@PostMapping("/changeStatus")
@ResponseBody
public AjaxResult changeStatus(SysUser user) {
userService.checkUserAllowed(user);
userService.changeStatus(user);
return success();
} }
/** /**
@ -210,9 +238,9 @@ public class SysUserController extends BaseController
{ {
SysUser user = userService.selectUserById(userId); SysUser user = userService.selectUserById(userId);
// 获取用户所属的角色列表 // 获取用户所属的角色列表
List<SysRole> roles = roleService.selectRolesByUserId(userId); Set<SysRole> userRoles = userService.selectUserById(userId).getRoles();
mmap.put("user", user); mmap.put("user", user);
mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList())); mmap.put("userRoles", userRoles);
return prefix + "/authRole"; return prefix + "/authRole";
} }
@ -228,63 +256,4 @@ public class SysUserController extends BaseController
userService.insertUserAuth(userId, roleIds); userService.insertUserAuth(userId, roleIds);
return success(); return success();
} }
@RequiresPermissions("system:user:remove")
@Log(title = "用户管理", businessType = BusinessType.DELETE)
@PostMapping("/remove")
@ResponseBody
public AjaxResult remove(String ids)
{
try
{
return toAjax(userService.deleteUserByIds(ids));
}
catch (Exception e)
{
return error(e.getMessage());
}
}
/**
* 校验用户名
*/
@PostMapping("/checkLoginNameUnique")
@ResponseBody
public String checkLoginNameUnique(SysUser user)
{
return userService.checkLoginNameUnique(user.getLoginName());
}
/**
* 校验手机号码
*/
@PostMapping("/checkPhoneUnique")
@ResponseBody
public String checkPhoneUnique(SysUser user)
{
return userService.checkPhoneUnique(user);
}
/**
* 校验email邮箱
*/
@PostMapping("/checkEmailUnique")
@ResponseBody
public String checkEmailUnique(SysUser user)
{
return userService.checkEmailUnique(user);
}
/**
* 用户状态修改
*/
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@RequiresPermissions("system:user:edit")
@PostMapping("/changeStatus")
@ResponseBody
public AjaxResult changeStatus(SysUser user)
{
userService.checkUserAllowed(user);
return toAjax(userService.changeStatus(user));
}
} }

View File

@ -2,7 +2,7 @@
db: db:
# mysql, oracle, sqlserver # mysql, oracle, sqlserver
type: mysql type: mysql
name: framework name: framework_jpa
username: root username: root
password: root password: root
# 数据源配置 # 数据源配置
@ -13,7 +13,7 @@ spring:
druid: druid:
# 主库数据源 # 主库数据源
master: master:
url: jdbc:mysql://localhost:3306/${db.name}?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 url: jdbc:mysql://localhost:3306/${db.name}?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8
username: ${db.username} username: ${db.username}
password: ${db.password} password: ${db.password}
# 从库数据源 # 从库数据源

View File

@ -28,14 +28,6 @@ server:
# Tomcat启动初始化的线程数默认值25 # Tomcat启动初始化的线程数默认值25
min-spare-threads: 30 min-spare-threads: 30
# 日志配置
logging:
level:
root: warn
com.ruoyi: debug
com.ruoyi.quartz.mapper: warn
com.ruoyi.system.mapper: warn
# 用户配置 # 用户配置
user: user:
password: password:
@ -86,22 +78,6 @@ spring:
jcache: jcache:
provider: org.ehcache.jsr107.EhcacheCachingProvider provider: org.ehcache.jsr107.EhcacheCachingProvider
# MyBatis
mybatis:
# 搜索指定包别名
typeAliasesPackage: com.ruoyi.**.domain
# 配置mapper的扫描找到所有的mapper.xml映射文件
mapperLocations: classpath*:mapper/**/*Mapper.xml
# 加载全局的配置文件
configLocation: classpath:mybatis/mybatis-config.xml
# PageHelper分页插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
# Shiro # Shiro
shiro: shiro:
user: user:

View File

@ -1,24 +1,2 @@
Application Version: ${ruoyi.version} Application Version: ${ruoyi.version}
Spring Boot Version: ${spring-boot.version} Spring Boot Version: ${spring-boot.version}
////////////////////////////////////////////////////////////////////
// _ooOoo_ //
// o8888888o //
// 88" . "88 //
// (| ^_^ |) //
// O\ = /O //
// ____/`---'\____ //
// .' \\| |// `. //
// / \\||| : |||// \ //
// / _||||| -:- |||||- \ //
// | | \\\ - /// | | //
// | \_| ''\---/'' | | //
// \ .-\__ `-` ___/-. / //
// ___`. .' /--.--\ `. . ___ //
// ."" '< `.___\_<|>_/___.' >'"". //
// | | : `- \`.;`\ _ /`;.`/ - ` : | | //
// \ \ `-. \_ __\ /__ _/ .-` / / //
// ========`-.____`-.___\_____/___.-`____.-'======== //
// `=---=' //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// 佛祖保佑 永不宕机 永无BUG //
////////////////////////////////////////////////////////////////////

View File

@ -3,11 +3,11 @@
-- ---------------------------- -- ----------------------------
drop table if exists sys_dept; drop table if exists sys_dept;
create table sys_dept ( create table sys_dept (
dept_id bigint(20) not null auto_increment comment '部门id', dept_id bigint not null auto_increment comment '部门id',
parent_id bigint(20) default 0 comment '父部门id', parent_id bigint default 0 comment '父部门id',
ancestors varchar(50) default '' comment '祖级列表', ancestors varchar(50) default '' comment '祖级列表',
dept_name varchar(30) default '' comment '部门名称', dept_name varchar(30) default '' comment '部门名称',
order_num int(4) default 0 comment '显示顺序', order_num int default 0 comment '显示顺序',
leader varchar(20) default null comment '负责人', leader varchar(20) default null comment '负责人',
phone varchar(11) default null comment '联系电话', phone varchar(11) default null comment '联系电话',
email varchar(50) default null comment '邮箱', email varchar(50) default null comment '邮箱',
@ -40,8 +40,8 @@ insert into sys_dept values(109, 102, '0,100,102', '财务部门', 2, '若
-- ---------------------------- -- ----------------------------
drop table if exists sys_user; drop table if exists sys_user;
create table sys_user ( create table sys_user (
user_id bigint(20) not null auto_increment comment '用户ID', user_id bigint not null auto_increment comment '用户ID',
dept_id bigint(20) default null comment '部门ID', dept_id bigint default null comment '部门ID',
login_name varchar(30) not null comment '登录账号', login_name varchar(30) not null comment '登录账号',
user_name varchar(30) default '' comment '用户昵称', user_name varchar(30) default '' comment '用户昵称',
user_type varchar(2) default '00' comment '用户类型00系统用户 01注册用户', user_type varchar(2) default '00' comment '用户类型00系统用户 01注册用户',
@ -76,10 +76,10 @@ insert into sys_user values(2, 105, 'ry', '若依', '00', 'ry@qq.com', '156
drop table if exists sys_post; drop table if exists sys_post;
create table sys_post create table sys_post
( (
post_id bigint(20) not null auto_increment comment '岗位ID', post_id bigint not null auto_increment comment '岗位ID',
post_code varchar(64) not null comment '岗位编码', post_code varchar(64) not null comment '岗位编码',
post_name varchar(50) not null comment '岗位名称', post_name varchar(50) not null comment '岗位名称',
post_sort int(4) not null comment '显示顺序', post_sort int not null comment '显示顺序',
status char(1) not null comment '状态0正常 1停用', status char(1) not null comment '状态0正常 1停用',
create_by varchar(64) default '' comment '创建者', create_by varchar(64) default '' comment '创建者',
create_time datetime comment '创建时间', create_time datetime comment '创建时间',
@ -103,10 +103,10 @@ insert into sys_post values(4, 'user', '普通员工', 4, '0', 'admin', '2018-0
-- ---------------------------- -- ----------------------------
drop table if exists sys_role; drop table if exists sys_role;
create table sys_role ( create table sys_role (
role_id bigint(20) not null auto_increment comment '角色ID', role_id bigint not null auto_increment comment '角色ID',
role_name varchar(30) not null comment '角色名称', role_name varchar(30) not null comment '角色名称',
role_key varchar(100) not null comment '角色权限字符串', role_key varchar(100) not null comment '角色权限字符串',
role_sort int(4) not null comment '显示顺序', role_sort int not null comment '显示顺序',
data_scope char(1) default '1' comment '数据范围1全部数据权限 2自定数据权限 3本部门数据权限 4本部门及以下数据权限', data_scope char(1) default '1' comment '数据范围1全部数据权限 2自定数据权限 3本部门数据权限 4本部门及以下数据权限',
status char(1) not null comment '角色状态0正常 1停用', status char(1) not null comment '角色状态0正常 1停用',
del_flag char(1) default '0' comment '删除标志0代表存在 2代表删除', del_flag char(1) default '0' comment '删除标志0代表存在 2代表删除',
@ -130,10 +130,10 @@ insert into sys_role values('2', '普通角色', 'common', 2, 2, '0', '0', 'ad
-- ---------------------------- -- ----------------------------
drop table if exists sys_menu; drop table if exists sys_menu;
create table sys_menu ( create table sys_menu (
menu_id bigint(20) not null auto_increment comment '菜单ID', menu_id bigint not null auto_increment comment '菜单ID',
menu_name varchar(50) not null comment '菜单名称', menu_name varchar(50) not null comment '菜单名称',
parent_id bigint(20) default 0 comment '父菜单ID', parent_id bigint default 0 comment '父菜单ID',
order_num int(4) default 0 comment '显示顺序', order_num int default 0 comment '显示顺序',
url varchar(200) default '#' comment '请求地址', url varchar(200) default '#' comment '请求地址',
target varchar(20) default '' comment '打开方式menuItem页签 menuBlank新窗口', target varchar(20) default '' comment '打开方式menuItem页签 menuBlank新窗口',
menu_type char(1) default '' comment '菜单类型M目录 C菜单 F按钮', menu_type char(1) default '' comment '菜单类型M目录 C菜单 F按钮',
@ -258,8 +258,8 @@ insert into sys_menu values('1061', '生成代码', '114', '5', '#', '', 'F', '
-- ---------------------------- -- ----------------------------
drop table if exists sys_user_role; drop table if exists sys_user_role;
create table sys_user_role ( create table sys_user_role (
user_id bigint(20) not null comment '用户ID', user_id bigint not null comment '用户ID',
role_id bigint(20) not null comment '角色ID', role_id bigint not null comment '角色ID',
primary key(user_id, role_id) primary key(user_id, role_id)
) engine=innodb comment = '用户和角色关联表'; ) engine=innodb comment = '用户和角色关联表';
@ -275,8 +275,8 @@ insert into sys_user_role values ('2', '2');
-- ---------------------------- -- ----------------------------
drop table if exists sys_role_menu; drop table if exists sys_role_menu;
create table sys_role_menu ( create table sys_role_menu (
role_id bigint(20) not null comment '角色ID', role_id bigint not null comment '角色ID',
menu_id bigint(20) not null comment '菜单ID', menu_id bigint not null comment '菜单ID',
primary key(role_id, menu_id) primary key(role_id, menu_id)
) engine=innodb comment = '角色和菜单关联表'; ) engine=innodb comment = '角色和菜单关联表';
@ -373,8 +373,8 @@ insert into sys_role_menu values ('2', '1061');
-- ---------------------------- -- ----------------------------
drop table if exists sys_role_dept; drop table if exists sys_role_dept;
create table sys_role_dept ( create table sys_role_dept (
role_id bigint(20) not null comment '角色ID', role_id bigint not null comment '角色ID',
dept_id bigint(20) not null comment '部门ID', dept_id bigint not null comment '部门ID',
primary key(role_id, dept_id) primary key(role_id, dept_id)
) engine=innodb comment = '角色和部门关联表'; ) engine=innodb comment = '角色和部门关联表';
@ -391,8 +391,8 @@ insert into sys_role_dept values ('2', '105');
drop table if exists sys_user_post; drop table if exists sys_user_post;
create table sys_user_post create table sys_user_post
( (
user_id bigint(20) not null comment '用户ID', user_id bigint not null comment '用户ID',
post_id bigint(20) not null comment '岗位ID', post_id bigint not null comment '岗位ID',
primary key (user_id, post_id) primary key (user_id, post_id)
) engine=innodb comment = '用户与岗位关联表'; ) engine=innodb comment = '用户与岗位关联表';
@ -408,12 +408,12 @@ insert into sys_user_post values ('2', '2');
-- ---------------------------- -- ----------------------------
drop table if exists sys_oper_log; drop table if exists sys_oper_log;
create table sys_oper_log ( create table sys_oper_log (
oper_id bigint(20) not null auto_increment comment '日志主键', oper_id bigint not null auto_increment comment '日志主键',
title varchar(50) default '' comment '模块标题', title varchar(50) default '' comment '模块标题',
business_type int(2) default 0 comment '业务类型0其它 1新增 2修改 3删除', business_type int default 0 comment '业务类型0其它 1新增 2修改 3删除',
method varchar(100) default '' comment '方法名称', method varchar(100) default '' comment '方法名称',
request_method varchar(10) default '' comment '请求方式', request_method varchar(10) default '' comment '请求方式',
operator_type int(1) default 0 comment '操作类别0其它 1后台用户 2手机端用户', operator_type int default 0 comment '操作类别0其它 1后台用户 2手机端用户',
oper_name varchar(50) default '' comment '操作人员', oper_name varchar(50) default '' comment '操作人员',
dept_name varchar(50) default '' comment '部门名称', dept_name varchar(50) default '' comment '部门名称',
oper_url varchar(255) default '' comment '请求URL', oper_url varchar(255) default '' comment '请求URL',
@ -421,7 +421,7 @@ create table sys_oper_log (
oper_location varchar(255) default '' comment '操作地点', oper_location varchar(255) default '' comment '操作地点',
oper_param varchar(2000) default '' comment '请求参数', oper_param varchar(2000) default '' comment '请求参数',
json_result varchar(2000) default '' comment '返回参数', json_result varchar(2000) default '' comment '返回参数',
status int(1) default 0 comment '操作状态0正常 1异常', status int default 0 comment '操作状态0正常 1异常',
error_msg varchar(2000) default '' comment '错误消息', error_msg varchar(2000) default '' comment '错误消息',
oper_time datetime comment '操作时间', oper_time datetime comment '操作时间',
primary key (oper_id) primary key (oper_id)
@ -434,7 +434,7 @@ create table sys_oper_log (
drop table if exists sys_dict_type; drop table if exists sys_dict_type;
create table sys_dict_type create table sys_dict_type
( (
dict_id bigint(20) not null auto_increment comment '字典主键', dict_id bigint not null auto_increment comment '字典主键',
dict_name varchar(100) default '' comment '字典名称', dict_name varchar(100) default '' comment '字典名称',
dict_type varchar(100) default '' comment '字典类型', dict_type varchar(100) default '' comment '字典类型',
status char(1) default '0' comment '状态0正常 1停用', status char(1) default '0' comment '状态0正常 1停用',
@ -465,8 +465,8 @@ insert into sys_dict_type values(10, '系统状态', 'sys_common_status', '0',
drop table if exists sys_dict_data; drop table if exists sys_dict_data;
create table sys_dict_data create table sys_dict_data
( (
dict_code bigint(20) not null auto_increment comment '字典编码', dict_code bigint not null auto_increment comment '字典编码',
dict_sort int(4) default 0 comment '字典排序', dict_sort int default 0 comment '字典排序',
dict_label varchar(100) default '' comment '字典标签', dict_label varchar(100) default '' comment '字典标签',
dict_value varchar(100) default '' comment '字典键值', dict_value varchar(100) default '' comment '字典键值',
dict_type varchar(100) default '' comment '字典类型', dict_type varchar(100) default '' comment '字典类型',
@ -518,7 +518,7 @@ insert into sys_dict_data values(29, 2, '失败', '1', 'sys_common_st
-- ---------------------------- -- ----------------------------
drop table if exists sys_config; drop table if exists sys_config;
create table sys_config ( create table sys_config (
config_id int(5) not null auto_increment comment '参数主键', config_id int not null auto_increment comment '参数主键',
config_name varchar(100) default '' comment '参数名称', config_name varchar(100) default '' comment '参数名称',
config_key varchar(100) default '' comment '参数键名', config_key varchar(100) default '' comment '参数键名',
config_value varchar(500) default '' comment '参数键值', config_value varchar(500) default '' comment '参数键值',
@ -545,7 +545,7 @@ insert into sys_config values(7, '主框架页-是否开启页脚', 'sys
-- ---------------------------- -- ----------------------------
drop table if exists sys_logininfor; drop table if exists sys_logininfor;
create table sys_logininfor ( create table sys_logininfor (
info_id bigint(20) not null auto_increment comment '访问ID', info_id bigint not null auto_increment comment '访问ID',
login_name varchar(50) default '' comment '登录账号', login_name varchar(50) default '' comment '登录账号',
ipaddr varchar(50) default '' comment '登录IP地址', ipaddr varchar(50) default '' comment '登录IP地址',
login_location varchar(255) default '' comment '登录地点', login_location varchar(255) default '' comment '登录地点',
@ -573,7 +573,7 @@ create table sys_user_online (
status varchar(10) default '' comment '在线状态on_line在线off_line离线', status varchar(10) default '' comment '在线状态on_line在线off_line离线',
start_timestamp datetime comment 'session创建时间', start_timestamp datetime comment 'session创建时间',
last_access_time datetime comment 'session最后访问时间', last_access_time datetime comment 'session最后访问时间',
expire_time int(5) default 0 comment '超时时间,单位为分钟', expire_time int default 0 comment '超时时间,单位为分钟',
primary key (sessionId) primary key (sessionId)
) engine=innodb comment = '在线用户记录'; ) engine=innodb comment = '在线用户记录';
@ -583,7 +583,7 @@ create table sys_user_online (
-- ---------------------------- -- ----------------------------
drop table if exists sys_job; drop table if exists sys_job;
create table sys_job ( create table sys_job (
job_id bigint(20) not null auto_increment comment '任务ID', job_id bigint not null auto_increment comment '任务ID',
job_name varchar(64) default '' comment '任务名称', job_name varchar(64) default '' comment '任务名称',
job_group varchar(64) default 'DEFAULT' comment '任务组名', job_group varchar(64) default 'DEFAULT' comment '任务组名',
invoke_target varchar(500) not null comment '调用目标字符串', invoke_target varchar(500) not null comment '调用目标字符串',
@ -609,7 +609,7 @@ insert into sys_job values(3, '系统默认(多参)', 'DEFAULT', 'ryTask.ryM
-- ---------------------------- -- ----------------------------
drop table if exists sys_job_log; drop table if exists sys_job_log;
create table sys_job_log ( create table sys_job_log (
job_log_id bigint(20) not null auto_increment comment '任务日志ID', job_log_id bigint not null auto_increment comment '任务日志ID',
job_name varchar(64) not null comment '任务名称', job_name varchar(64) not null comment '任务名称',
job_group varchar(64) not null comment '任务组名', job_group varchar(64) not null comment '任务组名',
invoke_target varchar(500) not null comment '调用目标字符串', invoke_target varchar(500) not null comment '调用目标字符串',
@ -626,7 +626,7 @@ create table sys_job_log (
-- ---------------------------- -- ----------------------------
drop table if exists sys_notice; drop table if exists sys_notice;
create table sys_notice ( create table sys_notice (
notice_id int(4) not null auto_increment comment '公告ID', notice_id int not null auto_increment comment '公告ID',
notice_title varchar(50) not null comment '公告标题', notice_title varchar(50) not null comment '公告标题',
notice_type char(1) not null comment '公告类型1通知 2公告', notice_type char(1) not null comment '公告类型1通知 2公告',
notice_content varchar(2000) default null comment '公告内容', notice_content varchar(2000) default null comment '公告内容',
@ -651,7 +651,7 @@ insert into sys_notice values('2', '维护通知2018-07-01 若依系统凌晨
-- ---------------------------- -- ----------------------------
drop table if exists gen_table; drop table if exists gen_table;
create table gen_table ( create table gen_table (
table_id bigint(20) not null auto_increment comment '编号', table_id bigint not null auto_increment comment '编号',
table_name varchar(200) default '' comment '表名称', table_name varchar(200) default '' comment '表名称',
table_comment varchar(500) default '' comment '表描述', table_comment varchar(500) default '' comment '表描述',
sub_table_name varchar(64) default null comment '关联子表的表名', sub_table_name varchar(64) default null comment '关联子表的表名',
@ -680,7 +680,7 @@ create table gen_table (
-- ---------------------------- -- ----------------------------
drop table if exists gen_table_column; drop table if exists gen_table_column;
create table gen_table_column ( create table gen_table_column (
column_id bigint(20) not null auto_increment comment '编号', column_id bigint not null auto_increment comment '编号',
table_id varchar(64) comment '归属表编号', table_id varchar(64) comment '归属表编号',
column_name varchar(200) comment '列名称', column_name varchar(200) comment '列名称',
column_comment varchar(500) comment '列描述', column_comment varchar(500) comment '列描述',

View File

@ -27,15 +27,15 @@ create table QRTZ_TRIGGERS (
job_name varchar(200) not null, job_name varchar(200) not null,
job_group varchar(200) not null, job_group varchar(200) not null,
description varchar(250) null, description varchar(250) null,
next_fire_time bigint(13) null, next_fire_time bigint null,
prev_fire_time bigint(13) null, prev_fire_time bigint null,
priority integer null, priority integer null,
trigger_state varchar(16) not null, trigger_state varchar(16) not null,
trigger_type varchar(8) not null, trigger_type varchar(8) not null,
start_time bigint(13) not null, start_time bigint not null,
end_time bigint(13) null, end_time bigint null,
calendar_name varchar(200) null, calendar_name varchar(200) null,
misfire_instr smallint(2) null, misfire_instr smallint null,
job_data blob null, job_data blob null,
primary key (sched_name,trigger_name,trigger_group), primary key (sched_name,trigger_name,trigger_group),
foreign key (sched_name,job_name,job_group) references QRTZ_JOB_DETAILS(sched_name,job_name,job_group) foreign key (sched_name,job_name,job_group) references QRTZ_JOB_DETAILS(sched_name,job_name,job_group)
@ -49,9 +49,9 @@ create table QRTZ_SIMPLE_TRIGGERS (
sched_name varchar(120) not null, sched_name varchar(120) not null,
trigger_name varchar(200) not null, trigger_name varchar(200) not null,
trigger_group varchar(200) not null, trigger_group varchar(200) not null,
repeat_count bigint(7) not null, repeat_count bigint not null,
repeat_interval bigint(12) not null, repeat_interval bigint not null,
times_triggered bigint(10) not null, times_triggered bigint not null,
primary key (sched_name,trigger_name,trigger_group), primary key (sched_name,trigger_name,trigger_group),
foreign key (sched_name,trigger_name,trigger_group) references QRTZ_TRIGGERS(sched_name,trigger_name,trigger_group) foreign key (sched_name,trigger_name,trigger_group) references QRTZ_TRIGGERS(sched_name,trigger_name,trigger_group)
) engine=innodb; ) engine=innodb;
@ -114,8 +114,8 @@ create table QRTZ_FIRED_TRIGGERS (
trigger_name varchar(200) not null, trigger_name varchar(200) not null,
trigger_group varchar(200) not null, trigger_group varchar(200) not null,
instance_name varchar(200) not null, instance_name varchar(200) not null,
fired_time bigint(13) not null, fired_time bigint not null,
sched_time bigint(13) not null, sched_time bigint not null,
priority integer not null, priority integer not null,
state varchar(16) not null, state varchar(16) not null,
job_name varchar(200) null, job_name varchar(200) null,
@ -132,8 +132,8 @@ drop table if exists QRTZ_SCHEDULER_STATE;
create table QRTZ_SCHEDULER_STATE ( create table QRTZ_SCHEDULER_STATE (
sched_name varchar(120) not null, sched_name varchar(120) not null,
instance_name varchar(200) not null, instance_name varchar(200) not null,
last_checkin_time bigint(13) not null, last_checkin_time bigint not null,
checkin_interval bigint(13) not null, checkin_interval bigint not null,
primary key (sched_name,instance_name) primary key (sched_name,instance_name)
) engine=innodb; ) engine=innodb;

View File

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!--输出到控制台-->
<appender name="Console" class="com.ruoyi.logger.MyConsoleAppender">
<withJansi>true</withJansi>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%black(%d) %highlight(%-5level) [%boldYellow(%t)] %boldGreen(%C{1.}:%method:%line) %msg%n%throwable
</Pattern>
</layout>
</appender>
<appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>D:/dustmonitor/logs/%d{yyyy-MM-dd}-%i.log</fileNamePattern>
<maxFileSize>10MB</maxFileSize>
<!-- 日志保存周期 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{HH:mm:ss} [%thread] %-5level %C{1.}:%method:%line - %msg%n</pattern>
</encoder>
</appender>
<root level="WARN">
<appender-ref ref="Console" />
<appender-ref ref="RollingFile" />
</root>
<logger name="com.ruoyi" level="INFO" additivity="false">
<appender-ref ref="Console" />
<appender-ref ref="RollingFile" />
</logger>
</configuration>

View File

@ -1,93 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 日志存放路径 -->
<property name="log.path" value="/home/ruoyi/logs" />
<!-- 日志输出格式 -->
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统日志输出 -->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 用户访问日志输出 -->
<appender name="sys-user" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-user.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 按天回滚 daily -->
<fileNamePattern>${log.path}/sys-user.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统模块日志级别控制 -->
<logger name="com.ruoyi" level="info" />
<!-- Spring日志级别控制 -->
<logger name="org.springframework" level="warn" />
<root level="info">
<appender-ref ref="console" />
</root>
<!--系统操作日志-->
<root level="info">
<appender-ref ref="file_info" />
<appender-ref ref="file_error" />
</root>
<!--系统用户操作日志-->
<logger name="sys-user" level="info">
<appender-ref ref="sys-user"/>
</logger>
</configuration>

View File

@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="true" /> <!-- 全局映射器启用缓存 -->
<setting name="useGeneratedKeys" value="true" /> <!-- 允许 JDBC 支持自动生成主键 -->
<setting name="defaultExecutorType" value="REUSE" /> <!-- 配置默认的执行器 -->
<setting name="logImpl" value="SLF4J" /> <!-- 指定 MyBatis 所用日志的具体实现 -->
<!-- <setting name="mapUnderscoreToCamelCase" value="true"/> 驼峰式命名 -->
</settings>
</configuration>

View File

@ -41,12 +41,6 @@
<artifactId>shiro-ehcache</artifactId> <artifactId>shiro-ehcache</artifactId>
</dependency> </dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
<!-- 自定义验证注解 --> <!-- 自定义验证注解 -->
<dependency> <dependency>
<groupId>javax.validation</groupId> <groupId>javax.validation</groupId>

View File

@ -1,9 +1,11 @@
package com.ruoyi.common.base; package com.ruoyi.common.base;
import com.ruoyi.common.core.text.Convert;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.NoRepositoryBean; import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
@ -12,4 +14,5 @@ import javax.persistence.criteria.Predicate;
public interface BaseRepository<T, ID> extends JpaRepository<T, ID>, public interface BaseRepository<T, ID> extends JpaRepository<T, ID>,
JpaSpecificationExecutor<T>, JpaSpecificationExecutor<T>,
QuerydslPredicateExecutor<T> { QuerydslPredicateExecutor<T> {
} }

View File

@ -1,8 +1,14 @@
package com.ruoyi.common.base; package com.ruoyi.common.base;
import com.querydsl.core.types.dsl.*; import com.querydsl.core.types.dsl.*;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.querydsl.ExpressionUtils; import com.ruoyi.common.utils.querydsl.ExpressionUtils;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.Function;
import java.util.stream.Collectors;
public class BaseService { public class BaseService {
protected BooleanExpression buildLike(StringPath path, String value){ protected BooleanExpression buildLike(StringPath path, String value){
@ -32,4 +38,25 @@ public class BaseService {
protected BooleanExpression notStartWith(StringPath path, String value){ protected BooleanExpression notStartWith(StringPath path, String value){
return ExpressionUtils.notStartWith(path, value); return ExpressionUtils.notStartWith(path, value);
} }
public static Collection<Long> toLongIterable(String str){
return Arrays.stream(Convert.toStrArray(str))
.map(Long::parseLong)
.collect(Collectors.toSet());
}
public static Collection<Integer> toIntegerIterable(String str){
return Arrays.stream(Convert.toStrArray(str))
.map(Integer::parseInt)
.collect(Collectors.toSet());
}
public static Collection<String> toStringIterable(String str){
return Arrays.stream(Convert.toStrArray(str))
.collect(Collectors.toSet());
}
protected <ID, ENTITY> Collection<ENTITY> toEntityIterable(Collection<ID> ids, Function<ID, ENTITY> function){
return Convert.toEntityIterable(ids, function);
}
} }

View File

@ -1,13 +1,17 @@
package com.ruoyi.common.core.text; package com.ruoyi.common.core.text;
import com.ruoyi.common.utils.StringUtils;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.text.NumberFormat; import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
import com.ruoyi.common.utils.StringUtils; import java.util.stream.Collectors;
/** /**
* 类型转换器 * 类型转换器
@ -314,6 +318,34 @@ public class Convert {
return toStrArray(",", str); return toStrArray(",", str);
} }
public static Collection<Long> toLongIterable(String str){
return toIdIterable(str, Long::parseLong);
}
public static Collection<Integer> toIntegerIterable(String str){
return toIdIterable(str, Integer::parseInt);
}
public static Collection<String> toStringIterable(String str){
return toIdIterable(str, s -> s);
}
public static <T> Collection<T> toIdIterable(String str, Function<String, T> function){
return Arrays.stream(toStrArray(str))
.map(function)
.collect(Collectors.toSet());
}
public static <ID, ENTITY> Collection<ENTITY> toIdIterable(String ids, Function<String, ID> toIDFunction, Function<ID, ENTITY> idToEntityFunction){
return toEntityIterable(toIdIterable(ids, toIDFunction), idToEntityFunction);
}
public static <ID, ENTITY> Collection<ENTITY> toEntityIterable(Collection<ID> ids, Function<ID, ENTITY> function){
return ids.stream()
.map(function)
.collect(Collectors.toSet());
}
/** /**
* 转换为String数组<br> * 转换为String数组<br>
* *

View File

@ -1,6 +1,14 @@
package com.ruoyi.framework.aspectj; package com.ruoyi.framework.aspectj;
import java.lang.reflect.Method; import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature; import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.After;

View File

@ -1,6 +1,6 @@
package com.ruoyi.framework.aspectj; package com.ruoyi.framework.aspectj;
import java.lang.reflect.Method; import java.util.Objects;
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Around;
@ -9,6 +9,7 @@ import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.ruoyi.common.annotation.DataSource; import com.ruoyi.common.annotation.DataSource;

View File

@ -65,8 +65,8 @@ public class SysRegisterService
{ {
user.setSalt(ShiroUtils.randomSalt()); user.setSalt(ShiroUtils.randomSalt());
user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt())); user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
boolean regFlag = userService.registerUser(user); user = userService.registerUser(user);
if (!regFlag) if (user == null)
{ {
msg = "注册失败,请联系系统管理人员"; msg = "注册失败,请联系系统管理人员";
} }

View File

@ -1,35 +1,28 @@
package com.ruoyi.generator.controller; package com.ruoyi.generator.controller;
import java.io.IOException; import com.ruoyi.common.annotation.Log;
import java.util.ArrayList; import com.ruoyi.common.core.controller.BaseController;
import java.util.List; import com.ruoyi.common.core.domain.AjaxResult;
import java.util.Map; import com.ruoyi.common.core.page.TableDataInfo;
import javax.servlet.http.HttpServletResponse; import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.security.PermissionUtils;
import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn;
import com.ruoyi.generator.service.IGenTableColumnService;
import com.ruoyi.generator.service.IGenTableService;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap; import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping; import java.io.IOException;
import org.springframework.web.bind.annotation.ResponseBody; import java.util.List;
import com.alibaba.fastjson.JSON; import java.util.Map;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.CxSelect;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.PermissionUtils;
import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn;
import com.ruoyi.generator.service.IGenTableColumnService;
import com.ruoyi.generator.service.IGenTableService;
/** /**
* 代码生成 操作处理 * 代码生成 操作处理
@ -38,8 +31,7 @@ import com.ruoyi.generator.service.IGenTableService;
*/ */
@Controller @Controller
@RequestMapping("/tool/gen") @RequestMapping("/tool/gen")
public class GenController extends BaseController public class GenController extends BaseController {
{
private String prefix = "tool/gen"; private String prefix = "tool/gen";
@Autowired @Autowired
@ -50,8 +42,7 @@ public class GenController extends BaseController
@RequiresPermissions("tool:gen:view") @RequiresPermissions("tool:gen:view")
@GetMapping() @GetMapping()
public String gen() public String gen() {
{
return prefix + "/gen"; return prefix + "/gen";
} }
@ -61,11 +52,8 @@ public class GenController extends BaseController
@RequiresPermissions("tool:gen:list") @RequiresPermissions("tool:gen:list")
@PostMapping("/list") @PostMapping("/list")
@ResponseBody @ResponseBody
public TableDataInfo genList(GenTable genTable) public TableDataInfo genList(GenTable genTable) {
{ return getDataTable(genTableService.selectGenTableList(genTable, getPageRequest()));
startPage();
List<GenTable> list = genTableService.selectGenTableList(genTable);
return getDataTable(list);
} }
/** /**
@ -74,11 +62,8 @@ public class GenController extends BaseController
@RequiresPermissions("tool:gen:list") @RequiresPermissions("tool:gen:list")
@PostMapping("/db/list") @PostMapping("/db/list")
@ResponseBody @ResponseBody
public TableDataInfo dataList(GenTable genTable) public TableDataInfo dataList(GenTable genTable) {
{ return getDataTable(genTableService.selectDbTableList(genTable, getPageRequest()));
startPage();
List<GenTable> list = genTableService.selectDbTableList(genTable);
return getDataTable(list);
} }
/** /**
@ -87,10 +72,9 @@ public class GenController extends BaseController
@RequiresPermissions("tool:gen:list") @RequiresPermissions("tool:gen:list")
@PostMapping("/column/list") @PostMapping("/column/list")
@ResponseBody @ResponseBody
public TableDataInfo columnList(GenTableColumn genTableColumn) public TableDataInfo columnList(GenTable genTable) {
{
TableDataInfo dataInfo = new TableDataInfo(); TableDataInfo dataInfo = new TableDataInfo();
List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(genTableColumn); List<GenTableColumn> list = genTableService.selectGenTableById(genTable.getTableId()).getColumns();
dataInfo.setRows(list); dataInfo.setRows(list);
dataInfo.setTotal(list.size()); dataInfo.setTotal(list.size());
return dataInfo; return dataInfo;
@ -101,8 +85,7 @@ public class GenController extends BaseController
*/ */
@RequiresPermissions("tool:gen:list") @RequiresPermissions("tool:gen:list")
@GetMapping("/importTable") @GetMapping("/importTable")
public String importTable() public String importTable() {
{
return prefix + "/importTable"; return prefix + "/importTable";
} }
@ -113,8 +96,7 @@ public class GenController extends BaseController
@Log(title = "代码生成", businessType = BusinessType.IMPORT) @Log(title = "代码生成", businessType = BusinessType.IMPORT)
@PostMapping("/importTable") @PostMapping("/importTable")
@ResponseBody @ResponseBody
public AjaxResult importTableSave(String tables) public AjaxResult importTableSave(String tables) {
{
String[] tableNames = Convert.toStrArray(tables); String[] tableNames = Convert.toStrArray(tables);
// 查询表信息 // 查询表信息
List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames); List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
@ -127,27 +109,9 @@ public class GenController extends BaseController
* 修改代码生成业务 * 修改代码生成业务
*/ */
@GetMapping("/edit/{tableId}") @GetMapping("/edit/{tableId}")
public String edit(@PathVariable("tableId") Long tableId, ModelMap mmap) public String edit(@PathVariable("tableId") Long tableId, ModelMap mmap) {
{
GenTable table = genTableService.selectGenTableById(tableId); GenTable table = genTableService.selectGenTableById(tableId);
List<GenTable> genTables = genTableService.selectGenTableAll();
List<CxSelect> cxSelect = new ArrayList<CxSelect>();
for (GenTable genTable : genTables)
{
if (!StringUtils.equals(table.getTableName(), genTable.getTableName()))
{
CxSelect cxTable = new CxSelect(genTable.getTableName(), genTable.getTableName() + '' + genTable.getTableComment());
List<CxSelect> cxColumns = new ArrayList<CxSelect>();
for (GenTableColumn tableColumn : genTable.getColumns())
{
cxColumns.add(new CxSelect(tableColumn.getColumnName(), tableColumn.getColumnName() + '' + tableColumn.getColumnComment()));
}
cxTable.setS(cxColumns);
cxSelect.add(cxTable);
}
}
mmap.put("table", table); mmap.put("table", table);
mmap.put("data", JSON.toJSON(cxSelect));
return prefix + "/edit"; return prefix + "/edit";
} }
@ -158,60 +122,12 @@ public class GenController extends BaseController
@Log(title = "代码生成", businessType = BusinessType.UPDATE) @Log(title = "代码生成", businessType = BusinessType.UPDATE)
@PostMapping("/edit") @PostMapping("/edit")
@ResponseBody @ResponseBody
public AjaxResult editSave(@Validated GenTable genTable) public AjaxResult editSave(@Validated GenTable genTable) {
{
genTableService.validateEdit(genTable); genTableService.validateEdit(genTable);
genTableService.updateGenTable(genTable); genTableService.updateGenTable(genTable);
return AjaxResult.success(); return AjaxResult.success();
} }
@RequiresPermissions("tool:gen:remove")
@Log(title = "代码生成", businessType = BusinessType.DELETE)
@PostMapping("/remove")
@ResponseBody
public AjaxResult remove(String ids)
{
genTableService.deleteGenTableByIds(ids);
return AjaxResult.success();
}
/**
* 预览代码
*/
@RequiresPermissions("tool:gen:preview")
@GetMapping("/preview/{tableId}")
@ResponseBody
public AjaxResult preview(@PathVariable("tableId") Long tableId) throws IOException
{
Map<String, String> dataMap = genTableService.previewCode(tableId);
return AjaxResult.success(dataMap);
}
/**
* 生成代码下载方式
*/
@RequiresPermissions("tool:gen:code")
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/download/{tableName}")
public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException
{
byte[] data = genTableService.downloadCode(tableName);
genCode(response, data);
}
/**
* 生成代码自定义路径
*/
@RequiresPermissions("tool:gen:code")
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/genCode/{tableName}")
@ResponseBody
public AjaxResult genCode(@PathVariable("tableName") String tableName)
{
genTableService.generatorCode(tableName);
return AjaxResult.success();
}
/** /**
* 同步数据库 * 同步数据库
*/ */
@ -225,6 +141,37 @@ public class GenController extends BaseController
return AjaxResult.success(); return AjaxResult.success();
} }
@RequiresPermissions("tool:gen:remove")
@Log(title = "代码生成", businessType = BusinessType.DELETE)
@PostMapping("/remove")
@ResponseBody
public AjaxResult remove(String ids) {
genTableService.deleteGenTableByIds(ids);
return AjaxResult.success();
}
/**
* 预览代码
*/
@RequiresPermissions("tool:gen:preview")
@GetMapping("/preview/{tableId}")
@ResponseBody
public AjaxResult preview(@PathVariable("tableId") Long tableId) throws IOException {
Map<String, String> dataMap = genTableService.previewCode(tableId);
return AjaxResult.success(dataMap);
}
/**
* 生成代码
*/
@RequiresPermissions("tool:gen:code")
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/genCode/{tableName}")
public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
byte[] data = genTableService.generatorCode(tableName);
genCode(response, data);
}
/** /**
* 批量生成代码 * 批量生成代码
*/ */
@ -232,18 +179,16 @@ public class GenController extends BaseController
@Log(title = "代码生成", businessType = BusinessType.GENCODE) @Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/batchGenCode") @GetMapping("/batchGenCode")
@ResponseBody @ResponseBody
public void batchGenCode(HttpServletResponse response, String tables) throws IOException public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
{
String[] tableNames = Convert.toStrArray(tables); String[] tableNames = Convert.toStrArray(tables);
byte[] data = genTableService.downloadCode(tableNames); byte[] data = genTableService.generatorCode(tableNames);
genCode(response, data); genCode(response, data);
} }
/** /**
* 生成zip文件 * 生成zip文件
*/ */
private void genCode(HttpServletResponse response, byte[] data) throws IOException private void genCode(HttpServletResponse response, byte[] data) throws IOException {
{
response.reset(); response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\""); response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
response.addHeader("Content-Length", "" + data.length); response.addHeader("Content-Length", "" + data.length);

View File

@ -1,372 +1,278 @@
package com.ruoyi.generator.domain; package com.ruoyi.generator.domain;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import org.apache.commons.lang3.ArrayUtils;
import com.ruoyi.common.constant.GenConstants; import com.ruoyi.common.constant.GenConstants;
import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
import javax.persistence.*;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
/** /**
* 业务表 gen_table * 业务表 gen_table
* *
* @author ruoyi * @author ruoyi
*/ */
public class GenTable extends BaseEntity @Entity
{ @Table(name = "gen_table")
public class GenTable extends BaseEntity {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 编号 */ /**
* 编号
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long tableId; private Long tableId;
/** 表名称 */ /**
* 表名称
*/
@NotBlank(message = "表名称不能为空") @NotBlank(message = "表名称不能为空")
private String tableName; private String tableName;
/** 表描述 */ /**
@NotBlank(message = "表描述不能为空") * 表描述
*/
private String tableComment; private String tableComment;
/** 关联父表的表名 */ /**
private String subTableName; * 实体类名称(首字母大写)
*/
/** 本表关联父表的外键名 */
private String subTableFkName;
/** 实体类名称(首字母大写) */
@NotBlank(message = "实体类名称不能为空") @NotBlank(message = "实体类名称不能为空")
private String className; private String className;
/** 使用的模板crud单表操作 tree树表操作 sub主子表操作 */ /**
* 使用的模板crud单表操作 tree树表操作
*/
private String tplCategory; private String tplCategory;
/** 生成包路径 */ /**
* 生成包路径
*/
@NotBlank(message = "生成包路径不能为空") @NotBlank(message = "生成包路径不能为空")
private String packageName; private String packageName;
/** 生成模块名 */ /**
* 生成模块名
*/
@NotBlank(message = "生成模块名不能为空") @NotBlank(message = "生成模块名不能为空")
private String moduleName; private String moduleName;
/** 生成业务名 */ /**
* 生成业务名
*/
@NotBlank(message = "生成业务名不能为空") @NotBlank(message = "生成业务名不能为空")
private String businessName; private String businessName;
/** 生成功能名 */ /**
@NotBlank(message = "生成功能名不能为空") * 生成功能名
*/
private String functionName; private String functionName;
/** 生成作者 */ /**
* 生成作者
*/
@NotBlank(message = "作者不能为空") @NotBlank(message = "作者不能为空")
private String functionAuthor; private String functionAuthor;
/** 生成代码方式0zip压缩包 1自定义路径 */ /**
private String genType; * 主键信息
*/
/** 生成路径(不填默认项目路径) */ @Transient
private String genPath;
/** 主键信息 */
private GenTableColumn pkColumn; private GenTableColumn pkColumn;
/** 子表信息 */ /**
private GenTable subTable; * 表列信息
*/
/** 表列信息 */
@Valid @Valid
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "gen_table_columns",
joinColumns = @JoinColumn(name = "genTableTableId", referencedColumnName = "tableId"),
inverseJoinColumns = @JoinColumn(name = "columnsColumnId", referencedColumnName = "columnId"))
@org.hibernate.annotations.ForeignKey(name = "none")
private List<GenTableColumn> columns; private List<GenTableColumn> columns;
/** 其它生成选项 */ /**
* 其它生成选项
*/
private String options; private String options;
/** 树编码字段 */ /**
* 树编码字段
*/
private String treeCode; private String treeCode;
/** 树父编码字段 */ /**
* 树父编码字段
*/
private String treeParentCode; private String treeParentCode;
/** 树名称字段 */ /**
* 树名称字段
*/
private String treeName; private String treeName;
/** 上级菜单ID字段 */ public Long getTableId() {
private String parentMenuId;
/** 上级菜单名称字段 */
private String parentMenuName;
public Long getTableId()
{
return tableId; return tableId;
} }
public void setTableId(Long tableId) public void setTableId(Long tableId) {
{
this.tableId = tableId; this.tableId = tableId;
} }
public String getTableName() public String getTableName() {
{
return tableName; return tableName;
} }
public void setTableName(String tableName) public void setTableName(String tableName) {
{
this.tableName = tableName; this.tableName = tableName;
} }
public String getTableComment() public String getTableComment() {
{
return tableComment; return tableComment;
} }
public void setTableComment(String tableComment) public void setTableComment(String tableComment) {
{
this.tableComment = tableComment; this.tableComment = tableComment;
} }
public String getSubTableName() public String getClassName() {
{
return subTableName;
}
public void setSubTableName(String subTableName)
{
this.subTableName = subTableName;
}
public String getSubTableFkName()
{
return subTableFkName;
}
public void setSubTableFkName(String subTableFkName)
{
this.subTableFkName = subTableFkName;
}
public String getClassName()
{
return className; return className;
} }
public void setClassName(String className) public void setClassName(String className) {
{
this.className = className; this.className = className;
} }
public String getTplCategory() public String getTplCategory() {
{
return tplCategory; return tplCategory;
} }
public void setTplCategory(String tplCategory) public void setTplCategory(String tplCategory) {
{
this.tplCategory = tplCategory; this.tplCategory = tplCategory;
} }
public String getPackageName() public String getPackageName() {
{
return packageName; return packageName;
} }
public void setPackageName(String packageName) public void setPackageName(String packageName) {
{
this.packageName = packageName; this.packageName = packageName;
} }
public String getModuleName() public String getModuleName() {
{
return moduleName; return moduleName;
} }
public void setModuleName(String moduleName) public void setModuleName(String moduleName) {
{
this.moduleName = moduleName; this.moduleName = moduleName;
} }
public String getBusinessName() public String getBusinessName() {
{
return businessName; return businessName;
} }
public void setBusinessName(String businessName) public void setBusinessName(String businessName) {
{
this.businessName = businessName; this.businessName = businessName;
} }
public String getFunctionName() public String getFunctionName() {
{
return functionName; return functionName;
} }
public void setFunctionName(String functionName) public void setFunctionName(String functionName) {
{
this.functionName = functionName; this.functionName = functionName;
} }
public String getFunctionAuthor() public String getFunctionAuthor() {
{
return functionAuthor; return functionAuthor;
} }
public void setFunctionAuthor(String functionAuthor) public void setFunctionAuthor(String functionAuthor) {
{
this.functionAuthor = functionAuthor; this.functionAuthor = functionAuthor;
} }
public String getGenType() public GenTableColumn getPkColumn() {
{
return genType;
}
public void setGenType(String genType)
{
this.genType = genType;
}
public String getGenPath()
{
return genPath;
}
public void setGenPath(String genPath)
{
this.genPath = genPath;
}
public GenTableColumn getPkColumn()
{
return pkColumn; return pkColumn;
} }
public void setPkColumn(GenTableColumn pkColumn) public void setPkColumn(GenTableColumn pkColumn) {
{
this.pkColumn = pkColumn; this.pkColumn = pkColumn;
} }
public GenTable getSubTable() public List<GenTableColumn> getColumns() {
{
return subTable;
}
public void setSubTable(GenTable subTable)
{
this.subTable = subTable;
}
public List<GenTableColumn> getColumns()
{
return columns; return columns;
} }
public void setColumns(List<GenTableColumn> columns) public void setColumns(List<GenTableColumn> columns) {
{
this.columns = columns; this.columns = columns;
} }
public String getOptions() public String getOptions() {
{
return options; return options;
} }
public void setOptions(String options) public void setOptions(String options) {
{
this.options = options; this.options = options;
} }
public String getTreeCode() public String getTreeCode() {
{
return treeCode; return treeCode;
} }
public void setTreeCode(String treeCode) public void setTreeCode(String treeCode) {
{
this.treeCode = treeCode; this.treeCode = treeCode;
} }
public String getTreeParentCode() public String getTreeParentCode() {
{
return treeParentCode; return treeParentCode;
} }
public void setTreeParentCode(String treeParentCode) public void setTreeParentCode(String treeParentCode) {
{
this.treeParentCode = treeParentCode; this.treeParentCode = treeParentCode;
} }
public String getTreeName() public String getTreeName() {
{
return treeName; return treeName;
} }
public void setTreeName(String treeName) public void setTreeName(String treeName) {
{
this.treeName = treeName; this.treeName = treeName;
} }
public String getParentMenuId() public boolean isTree() {
{
return parentMenuId;
}
public void setParentMenuId(String parentMenuId)
{
this.parentMenuId = parentMenuId;
}
public String getParentMenuName()
{
return parentMenuName;
}
public void setParentMenuName(String parentMenuName)
{
this.parentMenuName = parentMenuName;
}
public boolean isSub()
{
return isSub(this.tplCategory);
}
public static boolean isSub(String tplCategory)
{
return tplCategory != null && StringUtils.equals(GenConstants.TPL_SUB, tplCategory);
}
public boolean isTree()
{
return isTree(this.tplCategory); return isTree(this.tplCategory);
} }
public static boolean isTree(String tplCategory) public static boolean isTree(String tplCategory) {
{
return tplCategory != null && StringUtils.equals(GenConstants.TPL_TREE, tplCategory); return tplCategory != null && StringUtils.equals(GenConstants.TPL_TREE, tplCategory);
} }
public boolean isCrud() public boolean isCrud() {
{
return isCrud(this.tplCategory); return isCrud(this.tplCategory);
} }
public static boolean isCrud(String tplCategory) public static boolean isCrud(String tplCategory) {
{
return tplCategory != null && StringUtils.equals(GenConstants.TPL_CRUD, tplCategory); return tplCategory != null && StringUtils.equals(GenConstants.TPL_CRUD, tplCategory);
} }
public boolean isSuperColumn(String javaField) public boolean isSuperColumn(String javaField) {
{
return isSuperColumn(this.tplCategory, javaField); return isSuperColumn(this.tplCategory, javaField);
} }
public static boolean isSuperColumn(String tplCategory, String javaField) public static boolean isSuperColumn(String tplCategory, String javaField) {
{ if (isTree(tplCategory)) {
if (isTree(tplCategory)) StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.TREE_ENTITY);
{
return StringUtils.equalsAnyIgnoreCase(javaField,
ArrayUtils.addAll(GenConstants.TREE_ENTITY, GenConstants.BASE_ENTITY));
} }
return StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY); return StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY);
} }
public GenTable() {
}
public GenTable(Long tableId) {
this.tableId = tableId;
}
} }

View File

@ -1,373 +1,172 @@
package com.ruoyi.generator.domain; package com.ruoyi.generator.domain;
import javax.validation.constraints.NotBlank;
import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
/** /**
* 代码生成业务字段表 gen_table_column * 代码生成业务字段表 gen_table_column
* *
* @author ruoyi * @author ruoyi
*/ */
public class GenTableColumn extends BaseEntity @Data
{ @Entity
@Table(name = "gen_table_column")
public class GenTableColumn extends BaseEntity {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 编号 */ /**
* 编号
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long columnId; private Long columnId;
/** 归属表编号 */ /**
private Long tableId; * 列名称
*/
/** 列名称 */
private String columnName; private String columnName;
/** 列描述 */ /**
* 列描述
*/
private String columnComment; private String columnComment;
/** 列类型 */ /**
* 列类型
*/
private String columnType; private String columnType;
/** JAVA类型 */ /**
* JAVA类型
*/
private String javaType; private String javaType;
/** JAVA字段名 */ /**
* JAVA字段名
*/
@NotBlank(message = "Java属性不能为空") @NotBlank(message = "Java属性不能为空")
private String javaField; private String javaField;
/** 是否主键1是 */ /**
* 是否主键1是
*/
private String isPk; private String isPk;
/** 是否自增1是 */ /**
* 是否自增1是
*/
private String isIncrement; private String isIncrement;
/** 是否必填1是 */ /**
* 是否必填1是
*/
private String isRequired; private String isRequired;
/** 是否为插入字段1是 */ /**
* 是否为插入字段1是
*/
private String isInsert; private String isInsert;
/** 是否编辑字段1是 */ /**
* 是否编辑字段1是
*/
private String isEdit; private String isEdit;
/** 是否列表字段1是 */ /**
* 是否列表字段1是
*/
private String isList; private String isList;
/** 是否查询字段1是 */ /**
* 是否查询字段1是
*/
private String isQuery; private String isQuery;
/** 查询方式EQ等于、NE不等于、GT大于、LT小于、LIKE模糊、BETWEEN范围 */ /**
* 查询方式EQ等于NE不等于GT大于LT小于LIKE模糊BETWEEN范围
*/
private String queryType; private String queryType;
/** 显示类型input文本框、textarea文本域、select下拉框、checkbox复选框、radio单选框、datetime日期控件、upload上传控件、summernote富文本控件 */ /**
* 显示类型input文本框textarea文本域select下拉框checkbox复选框radio单选框datetime日期控件
*/
private String htmlType; private String htmlType;
/** 字典类型 */ /**
* 字典类型
*/
private String dictType; private String dictType;
/** 排序 */ /**
* 排序
*/
private Integer sort; private Integer sort;
public void setColumnId(Long columnId) @Transient
{ public boolean isSuperColumn() {
this.columnId = columnId;
}
public Long getColumnId()
{
return columnId;
}
public void setTableId(Long tableId)
{
this.tableId = tableId;
}
public Long getTableId()
{
return tableId;
}
public void setColumnName(String columnName)
{
this.columnName = columnName;
}
public String getColumnName()
{
return columnName;
}
public void setColumnComment(String columnComment)
{
this.columnComment = columnComment;
}
public String getColumnComment()
{
return columnComment;
}
public void setColumnType(String columnType)
{
this.columnType = columnType;
}
public String getColumnType()
{
return columnType;
}
public void setJavaType(String javaType)
{
this.javaType = javaType;
}
public String getJavaType()
{
return javaType;
}
public void setJavaField(String javaField)
{
this.javaField = javaField;
}
public String getJavaField()
{
return javaField;
}
public String getCapJavaField()
{
return StringUtils.capitalize(javaField);
}
public void setIsPk(String isPk)
{
this.isPk = isPk;
}
public String getIsPk()
{
return isPk;
}
public boolean isPk()
{
return isPk(this.isPk);
}
public boolean isPk(String isPk)
{
return isPk != null && StringUtils.equals("1", isPk);
}
public String getIsIncrement()
{
return isIncrement;
}
public void setIsIncrement(String isIncrement)
{
this.isIncrement = isIncrement;
}
public boolean isIncrement()
{
return isIncrement(this.isIncrement);
}
public boolean isIncrement(String isIncrement)
{
return isIncrement != null && StringUtils.equals("1", isIncrement);
}
public void setIsRequired(String isRequired)
{
this.isRequired = isRequired;
}
public String getIsRequired()
{
return isRequired;
}
public boolean isRequired()
{
return isRequired(this.isRequired);
}
public boolean isRequired(String isRequired)
{
return isRequired != null && StringUtils.equals("1", isRequired);
}
public void setIsInsert(String isInsert)
{
this.isInsert = isInsert;
}
public String getIsInsert()
{
return isInsert;
}
public boolean isInsert()
{
return isInsert(this.isInsert);
}
public boolean isInsert(String isInsert)
{
return isInsert != null && StringUtils.equals("1", isInsert);
}
public void setIsEdit(String isEdit)
{
this.isEdit = isEdit;
}
public String getIsEdit()
{
return isEdit;
}
public boolean isEdit()
{
return isInsert(this.isEdit);
}
public boolean isEdit(String isEdit)
{
return isEdit != null && StringUtils.equals("1", isEdit);
}
public void setIsList(String isList)
{
this.isList = isList;
}
public String getIsList()
{
return isList;
}
public boolean isList()
{
return isList(this.isList);
}
public boolean isList(String isList)
{
return isList != null && StringUtils.equals("1", isList);
}
public void setIsQuery(String isQuery)
{
this.isQuery = isQuery;
}
public String getIsQuery()
{
return isQuery;
}
public boolean isQuery()
{
return isQuery(this.isQuery);
}
public boolean isQuery(String isQuery)
{
return isQuery != null && StringUtils.equals("1", isQuery);
}
public void setQueryType(String queryType)
{
this.queryType = queryType;
}
public String getQueryType()
{
return queryType;
}
public String getHtmlType()
{
return htmlType;
}
public void setHtmlType(String htmlType)
{
this.htmlType = htmlType;
}
public void setDictType(String dictType)
{
this.dictType = dictType;
}
public String getDictType()
{
return dictType;
}
public void setSort(Integer sort)
{
this.sort = sort;
}
public Integer getSort()
{
return sort;
}
public boolean isSuperColumn()
{
return isSuperColumn(this.javaField); return isSuperColumn(this.javaField);
} }
public static boolean isSuperColumn(String javaField) public static boolean isSuperColumn(String javaField) {
{
return StringUtils.equalsAnyIgnoreCase(javaField, return StringUtils.equalsAnyIgnoreCase(javaField,
// BaseEntity //BaseEntity
"createBy", "createTime", "updateBy", "updateTime", "remark", "createBy", "createTime", "updateBy", "updateTime", "remark",
// TreeEntity //TreeEntity
"parentName", "parentId", "orderNum", "ancestors"); "parentName", "parentId", "orderNum", "ancestors");
} }
public boolean isUsableColumn() @Transient
{ public boolean isUsableColumn() {
return isUsableColumn(javaField); return isUsableColumn(javaField);
} }
public static boolean isUsableColumn(String javaField) public static boolean isUsableColumn(String javaField) {
{ //isSuperColumn()中的名单用于避免生成多余Domain属性若某些属性在生成页面时需要用到不能忽略则放在此处白名单
// isSuperColumn()中的名单用于避免生成多余Domain属性若某些属性在生成页面时需要用到不能忽略则放在此处白名单 return StringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum");
return StringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum", "remark");
} }
public String readConverterExp() public String readConverterExp() {
{
String remarks = StringUtils.substringBetween(this.columnComment, "", ""); String remarks = StringUtils.substringBetween(this.columnComment, "", "");
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
if (StringUtils.isNotEmpty(remarks)) if (StringUtils.isNotEmpty(remarks)) {
{ for (String value : remarks.split(" ")) {
for (String value : remarks.split(" ")) if (StringUtils.isNotEmpty(value)) {
{
if (StringUtils.isNotEmpty(value))
{
Object startStr = value.subSequence(0, 1); Object startStr = value.subSequence(0, 1);
String endStr = value.substring(1); String endStr = value.substring(1);
sb.append("").append(startStr).append("=").append(endStr).append(","); sb.append("").append(startStr).append("=").append(endStr).append(",");
} }
} }
return sb.deleteCharAt(sb.length() - 1).toString(); return sb.deleteCharAt(sb.length() - 1).toString();
} } else {
else
{
return this.columnComment; return this.columnComment;
} }
} }
public String capital(){
return StringUtils.capitalize(this.javaField);
}
@Transient
public boolean isList() {
return isList(this.isList);
}
@Transient
public boolean isList(String isList) {
return isList != null && StringUtils.equals("1", isList);
}
@Transient
public boolean isPk() {
return isPk(this.isPk);
}
@Transient
public boolean isPk(String isPk) {
return isPk != null && StringUtils.equals("1", isPk);
}
} }

View File

@ -1,23 +1,25 @@
package com.ruoyi.generator.service; package com.ruoyi.generator.service;
import com.ruoyi.generator.domain.GenTable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.ruoyi.generator.domain.GenTable;
/** /**
* 业务 服务层 * 业务 服务层
* *
* @author ruoyi * @author ruoyi
*/ */
public interface IGenTableService public interface IGenTableService {
{
/** /**
* 查询业务列表 * 查询业务列表
* *
* @param genTable 业务信息 * @param genTable 业务信息
* @return 业务集合 * @return 业务集合
*/ */
public List<GenTable> selectGenTableList(GenTable genTable); public Page<GenTable> selectGenTableList(GenTable genTable, Pageable pageable);
/** /**
* 查询据库列表 * 查询据库列表
@ -25,7 +27,7 @@ public interface IGenTableService
* @param genTable 业务信息 * @param genTable 业务信息
* @return 数据库表集合 * @return 数据库表集合
*/ */
public List<GenTable> selectDbTableList(GenTable genTable); public Page<GenTable> selectDbTableList(GenTable genTable, Pageable pageable);
/** /**
* 查询据库列表 * 查询据库列表
@ -35,13 +37,6 @@ public interface IGenTableService
*/ */
public List<GenTable> selectDbTableListByNames(String[] tableNames); public List<GenTable> selectDbTableListByNames(String[] tableNames);
/**
* 查询所有表信息
*
* @return 表信息集合
*/
public List<GenTable> selectGenTableAll();
/** /**
* 查询业务信息 * 查询业务信息
* *
@ -70,7 +65,7 @@ public interface IGenTableService
* 导入表结构 * 导入表结构
* *
* @param tableList 导入表列表 * @param tableList 导入表列表
* @param operName 操作人员 * @param operName 操作人员
*/ */
public void importGenTable(List<GenTable> tableList, String operName); public void importGenTable(List<GenTable> tableList, String operName);
@ -83,34 +78,20 @@ public interface IGenTableService
public Map<String, String> previewCode(Long tableId); public Map<String, String> previewCode(Long tableId);
/** /**
* 生成代码下载方式 * 生成代码
* *
* @param tableName 表名称 * @param tableName 表名称
* @return 数据 * @return 数据
*/ */
public byte[] downloadCode(String tableName); public byte[] generatorCode(String tableName);
/** /**
* 生成代码自定义路径 * 批量生成代码
*
* @param tableName 表名称
*/
public void generatorCode(String tableName);
/**
* 同步数据库
*
* @param tableName 表名称
*/
public void synchDb(String tableName);
/**
* 批量生成代码下载方式
* *
* @param tableNames 表数组 * @param tableNames 表数组
* @return 数据 * @return 数据
*/ */
public byte[] downloadCode(String[] tableNames); public byte[] generatorCode(String[] tableNames);
/** /**
* 修改保存参数校验 * 修改保存参数校验
@ -118,4 +99,11 @@ public interface IGenTableService
* @param genTable 业务信息 * @param genTable 业务信息
*/ */
public void validateEdit(GenTable genTable); public void validateEdit(GenTable genTable);
/**
* 同步数据库
*
* @param tableName 表名称
*/
public void synchDb(String tableName);
} }

View File

@ -1,15 +1,24 @@
package com.ruoyi.generator.service.impl; package com.ruoyi.generator.service.impl;
import java.io.ByteArrayOutputStream; import com.alibaba.fastjson.JSON;
import java.io.File; import com.alibaba.fastjson.JSONObject;
import java.io.IOException; import com.querydsl.core.types.ExpressionUtils;
import java.io.StringWriter; import com.querydsl.core.types.Predicate;
import java.util.LinkedHashMap; import com.ruoyi.common.base.BaseService;
import java.util.List; import com.ruoyi.common.constant.Constants;
import java.util.Map; import com.ruoyi.common.constant.GenConstants;
import java.util.stream.Collectors; import com.ruoyi.common.core.text.Convert;
import java.util.zip.ZipEntry; import com.ruoyi.common.exception.BusinessException;
import java.util.zip.ZipOutputStream; import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn;
import com.ruoyi.generator.domain.QGenTable;
import com.ruoyi.generator.repository.GenTableColumnRepository;
import com.ruoyi.generator.repository.GenTableRepository;
import com.ruoyi.generator.service.IGenTableService;
import com.ruoyi.generator.util.GenUtils;
import com.ruoyi.generator.util.VelocityInitializer;
import com.ruoyi.generator.util.VelocityUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template; import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext; import org.apache.velocity.VelocityContext;
@ -17,25 +26,24 @@ import org.apache.velocity.app.Velocity;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import java.io.ByteArrayOutputStream;
import com.ruoyi.common.constant.Constants; import java.io.IOException;
import com.ruoyi.common.constant.GenConstants; import java.io.StringWriter;
import com.ruoyi.common.core.text.CharsetKit; import java.util.ArrayList;
import com.ruoyi.common.core.text.Convert; import java.util.LinkedHashMap;
import com.ruoyi.common.exception.BusinessException; import java.util.List;
import com.ruoyi.common.utils.StringUtils; import java.util.Map;
import com.ruoyi.common.utils.file.FileUtils; import java.util.stream.Collectors;
import com.ruoyi.generator.domain.GenTable; import java.util.zip.ZipEntry;
import com.ruoyi.generator.domain.GenTableColumn; import java.util.zip.ZipOutputStream;
import com.ruoyi.generator.mapper.GenTableColumnMapper;
import com.ruoyi.generator.mapper.GenTableMapper;
import com.ruoyi.generator.service.IGenTableService;
import com.ruoyi.generator.util.GenUtils;
import com.ruoyi.generator.util.VelocityInitializer;
import com.ruoyi.generator.util.VelocityUtils;
/** /**
* 业务 服务层实现 * 业务 服务层实现
@ -43,15 +51,18 @@ import com.ruoyi.generator.util.VelocityUtils;
* @author ruoyi * @author ruoyi
*/ */
@Service @Service
public class GenTableServiceImpl implements IGenTableService public class GenTableServiceImpl extends BaseService implements IGenTableService {
{
private static final String QUARTZ_TABLE_PREFIX = "qrtz_";
private static final String GEN_TABLE_PREFIX = "gen_";
private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class); private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class);
@Autowired @Autowired
private GenTableMapper genTableMapper; private GenTableRepository genTableRepository;
@Autowired @Autowired
private GenTableColumnMapper genTableColumnMapper; private JdbcTemplate jdbcTemplate;
@Autowired
private GenTableColumnRepository genTableColumnRepository;
/** /**
* 查询业务信息 * 查询业务信息
@ -60,9 +71,8 @@ public class GenTableServiceImpl implements IGenTableService
* @return 业务信息 * @return 业务信息
*/ */
@Override @Override
public GenTable selectGenTableById(Long id) public GenTable selectGenTableById(Long id) {
{ GenTable genTable = genTableRepository.findById(id).get();
GenTable genTable = genTableMapper.selectGenTableById(id);
setTableFromOptions(genTable); setTableFromOptions(genTable);
return genTable; return genTable;
} }
@ -74,9 +84,8 @@ public class GenTableServiceImpl implements IGenTableService
* @return 业务集合 * @return 业务集合
*/ */
@Override @Override
public List<GenTable> selectGenTableList(GenTable genTable) public Page<GenTable> selectGenTableList(GenTable genTable, Pageable pageable) {
{ return genTableRepository.findAll(getPredicate(genTable), pageable);
return genTableMapper.selectGenTableList(genTable);
} }
/** /**
@ -85,10 +94,44 @@ public class GenTableServiceImpl implements IGenTableService
* @param genTable 业务信息 * @param genTable 业务信息
* @return 数据库表集合 * @return 数据库表集合
*/ */
@Override public Page<GenTable> selectDbTableList(GenTable genTable, Pageable pageable) {
public List<GenTable> selectDbTableList(GenTable genTable) String sql = " select table_name, table_comment, create_time, update_time from information_schema.tables " +
{ " where table_schema = (select database()) " +
return genTableMapper.selectDbTableList(genTable); " AND table_name NOT LIKE '"+QUARTZ_TABLE_PREFIX+"%' AND table_name NOT LIKE '"+GEN_TABLE_PREFIX+"%' " +
" AND table_name NOT IN (select table_name from gen_table) ";
if(StringUtils.isNotEmpty(genTable.getTableName())){
sql += " AND lower(table_name) like lower(concat('%', " + genTable.getTableName()+ ", '%')) ";
}
if(StringUtils.isNotEmpty(genTable.getTableName())){
sql += " AND lower(table_comment) like lower(concat('%', " + genTable.getTableComment() + ", '%'))";
}
String countSql = "select count(0) from ( " + sql + " ) t";
if(pageable.isPaged()){
int page = pageable.getPageNumber();
int size = pageable.getPageSize();
int start = 0;
if(page > 0){
start = page * size ;
}
sql += " limit " + start + "," + size;
}
List<GenTable> tables = jdbcTemplate.query(sql, new BeanPropertyRowMapper<GenTable>(GenTable.class));
int count = jdbcTemplate.queryForObject(countSql, Integer.class);
return new PageImpl<GenTable>(tables, pageable, count);
}
private Predicate getPredicate(GenTable genTable){
QGenTable qGenTable = QGenTable.genTable;
List<Predicate> predicates = new ArrayList<>();
predicates.add(notStartWith(qGenTable.tableName, QUARTZ_TABLE_PREFIX));
predicates.add(notStartWith(qGenTable.tableName, GEN_TABLE_PREFIX));
if(StringUtils.isNotEmpty(genTable.getTableName())){
predicates.add(buildLike(qGenTable.tableName, genTable.getTableName()));
}
if(StringUtils.isNotEmpty(genTable.getTableComment())){
predicates.add(buildLike(qGenTable.tableComment, genTable.getTableComment()));
}
return ExpressionUtils.allOf(predicates);
} }
/** /**
@ -97,21 +140,18 @@ public class GenTableServiceImpl implements IGenTableService
* @param tableNames 表名称组 * @param tableNames 表名称组
* @return 数据库表集合 * @return 数据库表集合
*/ */
@Override public List<GenTable> selectDbTableListByNames(String[] tableNames) {
public List<GenTable> selectDbTableListByNames(String[] tableNames) String sql = "select table_name, table_comment, create_time, update_time from information_schema.tables " +
{ " where table_name NOT LIKE '"+QUARTZ_TABLE_PREFIX+"%' and table_name NOT LIKE '"+GEN_TABLE_PREFIX+"%' and table_schema = (select database()) " +
return genTableMapper.selectDbTableListByNames(tableNames); " and table_name in (";
} for(int i=0;i<tableNames.length;i++){
sql += "'" +tableNames[i]+"'";
/** if(i != tableNames.length - 1){
* 查询所有表信息 sql += ",";
* }
* @return 表信息集合 }
*/ sql += ")";
@Override return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(GenTable.class));
public List<GenTable> selectGenTableAll()
{
return genTableMapper.selectGenTableAll();
} }
/** /**
@ -122,17 +162,12 @@ public class GenTableServiceImpl implements IGenTableService
*/ */
@Override @Override
@Transactional @Transactional
public void updateGenTable(GenTable genTable) public void updateGenTable(GenTable genTable) {
{
String options = JSON.toJSONString(genTable.getParams()); String options = JSON.toJSONString(genTable.getParams());
genTable.setOptions(options); genTable.setOptions(options);
int row = genTableMapper.updateGenTable(genTable); genTableRepository.save(genTable);
if (row > 0) for (GenTableColumn cenTableColumn : genTable.getColumns()) {
{ genTableColumnRepository.save(cenTableColumn);
for (GenTableColumn cenTableColumn : genTable.getColumns())
{
genTableColumnMapper.updateGenTableColumn(cenTableColumn);
}
} }
} }
@ -144,45 +179,39 @@ public class GenTableServiceImpl implements IGenTableService
*/ */
@Override @Override
@Transactional @Transactional
public void deleteGenTableByIds(String ids) public void deleteGenTableByIds(String ids) {
{ for(Long id : Convert.toLongArray(ids)){
genTableMapper.deleteGenTableByIds(Convert.toLongArray(ids)); genTableRepository.deleteById(id);
genTableColumnMapper.deleteGenTableColumnByIds(Convert.toLongArray(ids)); }
} }
/** /**
* 导入表结构 * 导入表结构
* *
* @param tableList 导入表列表 * @param tableList 导入表列表
* @param operName 操作人员 * @param operName 操作人员
*/ */
@Override @Override
@Transactional @Transactional
public void importGenTable(List<GenTable> tableList, String operName) public void importGenTable(List<GenTable> tableList, String operName) {
{ for (GenTable table : tableList) {
try try {
{
for (GenTable table : tableList)
{
String tableName = table.getTableName();
GenUtils.initTable(table, operName); GenUtils.initTable(table, operName);
int row = genTableMapper.insertGenTable(table); List<GenTableColumn> columns = new ArrayList<>();
if (row > 0) String sql = "select column_name, (case when (is_nullable = 'no' && column_key != 'PRI') then '1' else null end) as is_required, (case when column_key = 'PRI' then '1' else '0' end) as is_pk, ordinal_position as sort, column_comment, (case when extra = 'auto_increment' then '1' else '0' end) as is_increment, column_type " +
{ " from information_schema.columns where table_schema = (select database()) and table_name = '" + table.getTableName() + "'" +
// 保存列信息 " order by ordinal_position";
List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName); List<GenTableColumn> genTableColumns = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(GenTableColumn.class));
for (GenTableColumn column : genTableColumns) for (GenTableColumn column : genTableColumns) {
{ GenUtils.initColumnField(column, table);
GenUtils.initColumnField(column, table); columns.add(column);
genTableColumnMapper.insertGenTableColumn(column);
}
} }
table.setColumns(columns);
genTableRepository.save(table);
} catch (Exception e) {
log.error("表名 " + table.getTableName() + " 导入失败:", e);
} }
} }
catch (Exception e)
{
throw new BusinessException("导入失败:" + e.getMessage());
}
} }
/** /**
@ -191,24 +220,20 @@ public class GenTableServiceImpl implements IGenTableService
* @param tableId 表编号 * @param tableId 表编号
* @return 预览数据列表 * @return 预览数据列表
*/ */
@Override public Map<String, String> previewCode(Long tableId) {
public Map<String, String> previewCode(Long tableId)
{
Map<String, String> dataMap = new LinkedHashMap<>(); Map<String, String> dataMap = new LinkedHashMap<>();
// 查询表信息 // 查询表信息
GenTable table = genTableMapper.selectGenTableById(tableId); GenTable table = genTableRepository.findById(tableId).get();
// 设置主子表信息 // 查询列信息
setSubTable(table); List<GenTableColumn> columns = table.getColumns();
// 设置主键列信息 setPkColumn(table, columns);
setPkColumn(table);
VelocityInitializer.initVelocity(); VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table); VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表 // 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory()); List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) for (String template : templates) {
{
// 渲染模板 // 渲染模板
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8); Template tpl = Velocity.getTemplate(template, Constants.UTF8);
@ -219,14 +244,13 @@ public class GenTableServiceImpl implements IGenTableService
} }
/** /**
* 生成代码下载方式 * 生成代码
* *
* @param tableName 表名称 * @param tableName 表名称
* @return 数据 * @return 数据
*/ */
@Override @Override
public byte[] downloadCode(String tableName) public byte[] generatorCode(String tableName) {
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream); ZipOutputStream zip = new ZipOutputStream(outputStream);
generatorCode(tableName, zip); generatorCode(tableName, zip);
@ -235,19 +259,31 @@ public class GenTableServiceImpl implements IGenTableService
} }
/** /**
* 生成代码自定义路径 * 批量生成代码
* *
* @param tableName 表名称 * @param tableNames 表数组
* @return 数据
*/ */
@Override @Override
public void generatorCode(String tableName) public byte[] generatorCode(String[] tableNames) {
{ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
for (String tableName : tableNames) {
generatorCode(tableName, zip);
}
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
/**
* 查询表信息并生成代码
*/
private void generatorCode(String tableName, ZipOutputStream zip) {
// 查询表信息 // 查询表信息
GenTable table = genTableMapper.selectGenTableByName(tableName); GenTable table = genTableRepository.findFirstByTableName(tableName);
// 设置主子表信息 // 查询列信息
setSubTable(table); List<GenTableColumn> columns = table.getColumns();
// 设置主键列信息 setPkColumn(table, columns);
setPkColumn(table);
VelocityInitializer.initVelocity(); VelocityInitializer.initVelocity();
@ -255,27 +291,77 @@ public class GenTableServiceImpl implements IGenTableService
// 获取模板列表 // 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory()); List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) for (String template : templates) {
{ // 渲染模板
if (!StringUtils.contains(template, "sql.vm")) StringWriter sw = new StringWriter();
{ Template tpl = Velocity.getTemplate(template, Constants.UTF8);
// 渲染模板 tpl.merge(context, sw);
StringWriter sw = new StringWriter(); try {
Template tpl = Velocity.getTemplate(template, Constants.UTF8); // 添加到zip
tpl.merge(context, sw); zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
try IOUtils.write(sw.toString(), zip, Constants.UTF8);
{ IOUtils.closeQuietly(sw);
String path = getGenPath(table, template); zip.closeEntry();
FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8); } catch (IOException e) {
} log.error("渲染模板失败,表名:" + table.getTableName(), e);
catch (IOException e)
{
throw new BusinessException("渲染模板失败,表名:" + table.getTableName());
}
} }
} }
} }
/**
* 修改保存参数校验
*
* @param genTable 业务信息
*/
public void validateEdit(GenTable genTable) {
if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
String options = JSON.toJSONString(genTable.getParams());
JSONObject paramsObj = JSONObject.parseObject(options);
if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) {
throw new BusinessException("树编码字段不能为空");
} else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) {
throw new BusinessException("树父编码字段不能为空");
} else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) {
throw new BusinessException("树名称字段不能为空");
}
}
}
/**
* 设置主键列信息
*
* @param table 业务表信息
* @param columns 业务字段列表
*/
public void setPkColumn(GenTable table, List<GenTableColumn> columns) {
for (GenTableColumn column : columns) {
if (column.isPk()) {
table.setPkColumn(column);
break;
}
}
if (StringUtils.isNull(table.getPkColumn())) {
table.setPkColumn(columns.get(0));
}
}
/**
* 设置代码生成其他选项值
*
* @param genTable 设置后的生成对象
*/
public void setTableFromOptions(GenTable genTable) {
JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions());
if (StringUtils.isNotNull(paramsObj)) {
String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
String treeName = paramsObj.getString(GenConstants.TREE_NAME);
genTable.setTreeCode(treeCode);
genTable.setTreeParentCode(treeParentCode);
genTable.setTreeName(treeName);
}
}
/** /**
* 同步数据库 * 同步数据库
* *
@ -285,11 +371,11 @@ public class GenTableServiceImpl implements IGenTableService
@Transactional @Transactional
public void synchDb(String tableName) public void synchDb(String tableName)
{ {
GenTable table = genTableMapper.selectGenTableByName(tableName); GenTable table = genTableRepository.findFirstByTableName(tableName);
List<GenTableColumn> tableColumns = table.getColumns(); List<GenTableColumn> tableColumns = table.getColumns();
List<String> tableColumnNames = tableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList()); List<String> tableColumnNames = tableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName); List<GenTableColumn> dbTableColumns = table.getColumns();
if (StringUtils.isEmpty(dbTableColumns)) if (StringUtils.isEmpty(dbTableColumns))
{ {
throw new BusinessException("同步数据失败,原表结构不存在"); throw new BusinessException("同步数据失败,原表结构不存在");
@ -300,7 +386,7 @@ public class GenTableServiceImpl implements IGenTableService
if (!tableColumnNames.contains(column.getColumnName())) if (!tableColumnNames.contains(column.getColumnName()))
{ {
GenUtils.initColumnField(column, table); GenUtils.initColumnField(column, table);
genTableColumnMapper.insertGenTableColumn(column); genTableColumnRepository.save(column);
} }
}); });
@ -308,195 +394,7 @@ public class GenTableServiceImpl implements IGenTableService
.filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList()); .filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
if (StringUtils.isNotEmpty(delColumns)) if (StringUtils.isNotEmpty(delColumns))
{ {
genTableColumnMapper.deleteGenTableColumns(delColumns); genTableColumnRepository.deleteAll(delColumns);
} }
} }
/**
* 批量生成代码
*
* @param tableNames 表数组
* @return 数据
*/
@Override
public byte[] downloadCode(String[] tableNames)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
for (String tableName : tableNames)
{
generatorCode(tableName, zip);
}
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
/**
* 查询表信息并生成代码
*/
private void generatorCode(String tableName, ZipOutputStream zip)
{
// 查询表信息
GenTable table = genTableMapper.selectGenTableByName(tableName);
// 设置主子表信息
setSubTable(table);
// 设置主键列信息
setPkColumn(table);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates)
{
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
try
{
// 添加到zip
zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
IOUtils.write(sw.toString(), zip, Constants.UTF8);
IOUtils.closeQuietly(sw);
zip.flush();
zip.closeEntry();
}
catch (IOException e)
{
log.error("渲染模板失败,表名:" + table.getTableName(), e);
}
}
}
/**
* 修改保存参数校验
*
* @param genTable 业务信息
*/
@Override
public void validateEdit(GenTable genTable)
{
if (GenConstants.TPL_TREE.equals(genTable.getTplCategory()))
{
String options = JSON.toJSONString(genTable.getParams());
JSONObject paramsObj = JSONObject.parseObject(options);
if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE)))
{
throw new BusinessException("树编码字段不能为空");
}
else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE)))
{
throw new BusinessException("树父编码字段不能为空");
}
else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME)))
{
throw new BusinessException("树名称字段不能为空");
}
}
else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory()))
{
if (StringUtils.isEmpty(genTable.getSubTableName()))
{
throw new BusinessException("关联子表的表名不能为空");
}
else if (StringUtils.isEmpty(genTable.getSubTableFkName()))
{
throw new BusinessException("子表关联的外键名不能为空");
}
}
}
/**
* 设置主键列信息
*
* @param table 业务表信息
*/
public void setPkColumn(GenTable table)
{
for (GenTableColumn column : table.getColumns())
{
if (column.isPk())
{
table.setPkColumn(column);
break;
}
}
if (StringUtils.isNull(table.getPkColumn()))
{
table.setPkColumn(table.getColumns().get(0));
}
if (GenConstants.TPL_SUB.equals(table.getTplCategory()))
{
for (GenTableColumn column : table.getSubTable().getColumns())
{
if (column.isPk())
{
table.getSubTable().setPkColumn(column);
break;
}
}
if (StringUtils.isNull(table.getSubTable().getPkColumn()))
{
table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
}
}
}
/**
* 设置主子表信息
*
* @param table 业务表信息
*/
public void setSubTable(GenTable table)
{
String subTableName = table.getSubTableName();
if (StringUtils.isNotEmpty(subTableName))
{
table.setSubTable(genTableMapper.selectGenTableByName(subTableName));
}
}
/**
* 设置代码生成其他选项值
*
* @param genTable 设置后的生成对象
*/
public void setTableFromOptions(GenTable genTable)
{
JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions());
if (StringUtils.isNotNull(paramsObj))
{
String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
String treeName = paramsObj.getString(GenConstants.TREE_NAME);
String parentMenuId = paramsObj.getString(GenConstants.PARENT_MENU_ID);
String parentMenuName = paramsObj.getString(GenConstants.PARENT_MENU_NAME);
genTable.setTreeCode(treeCode);
genTable.setTreeParentCode(treeParentCode);
genTable.setTreeName(treeName);
genTable.setParentMenuId(parentMenuId);
genTable.setParentMenuName(parentMenuName);
}
}
/**
* 获取代码生成地址
*
* @param table 业务表信息
* @param template 模板文件路径
* @return 生成地址
*/
public static String getGenPath(GenTable table, String template)
{
String genPath = table.getGenPath();
if (StringUtils.equals(genPath, "/"))
{
return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
}
return genPath + File.separator + VelocityUtils.getFileName(template, table);
}
} }

View File

@ -1,25 +1,24 @@
package com.ruoyi.generator.util; package com.ruoyi.generator.util;
import java.util.Arrays;
import org.apache.commons.lang3.RegExUtils;
import com.ruoyi.common.constant.GenConstants; import com.ruoyi.common.constant.GenConstants;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.config.GenConfig; import com.ruoyi.generator.config.GenConfig;
import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn; import com.ruoyi.generator.domain.GenTableColumn;
import org.apache.commons.lang3.RegExUtils;
import java.util.Arrays;
/** /**
* 代码生成器 工具类 * 代码生成器 工具类
* *
* @author ruoyi * @author ruoyi
*/ */
public class GenUtils public class GenUtils {
{
/** /**
* 初始化表信息 * 初始化表信息
*/ */
public static void initTable(GenTable genTable, String operName) public static void initTable(GenTable genTable, String operName) {
{
genTable.setClassName(convertClassName(genTable.getTableName())); genTable.setClassName(convertClassName(genTable.getTableName()));
genTable.setPackageName(GenConfig.getPackageName()); genTable.setPackageName(GenConfig.getPackageName());
genTable.setModuleName(getModuleName(GenConfig.getPackageName())); genTable.setModuleName(getModuleName(GenConfig.getPackageName()));
@ -32,46 +31,36 @@ public class GenUtils
/** /**
* 初始化列属性字段 * 初始化列属性字段
*/ */
public static void initColumnField(GenTableColumn column, GenTable table) public static void initColumnField(GenTableColumn column, GenTable table) {
{
String dataType = getDbType(column.getColumnType()); String dataType = getDbType(column.getColumnType());
String columnName = column.getColumnName(); String columnName = column.getColumnName();
column.setTableId(table.getTableId());
column.setCreateBy(table.getCreateBy()); column.setCreateBy(table.getCreateBy());
// 设置java字段名 // 设置java字段名
column.setJavaField(StringUtils.toCamelCase(columnName)); column.setJavaField(StringUtils.toCamelCase(columnName));
if (arraysContains(GenConstants.COLUMNTYPE_STR, dataType)) if (arraysContains(GenConstants.COLUMNTYPE_STR, dataType)) {
{
column.setJavaType(GenConstants.TYPE_STRING); column.setJavaType(GenConstants.TYPE_STRING);
// 字符串长度超过500设置为文本域 // 字符串长度超过500设置为文本域
Integer columnLength = getColumnLength(column.getColumnType()); Integer columnLength = getColumnLength(column.getColumnType());
String htmlType = columnLength >= 500 ? GenConstants.HTML_TEXTAREA : GenConstants.HTML_INPUT; String htmlType = columnLength >= 500 ? GenConstants.HTML_TEXTAREA : GenConstants.HTML_INPUT;
column.setHtmlType(htmlType); column.setHtmlType(htmlType);
} } else if (arraysContains(GenConstants.COLUMNTYPE_TIME, dataType)) {
else if (arraysContains(GenConstants.COLUMNTYPE_TIME, dataType))
{
column.setJavaType(GenConstants.TYPE_DATE); column.setJavaType(GenConstants.TYPE_DATE);
column.setHtmlType(GenConstants.HTML_DATETIME); column.setHtmlType(GenConstants.HTML_DATETIME);
} } else if (arraysContains(GenConstants.COLUMNTYPE_NUMBER, dataType)) {
else if (arraysContains(GenConstants.COLUMNTYPE_NUMBER, dataType))
{
column.setHtmlType(GenConstants.HTML_INPUT); column.setHtmlType(GenConstants.HTML_INPUT);
// 如果是浮点型 // 如果是浮点型
String[] str = StringUtils.split(StringUtils.substringBetween(column.getColumnType(), "(", ")"), ","); String[] str = StringUtils.split(StringUtils.substringBetween(column.getColumnType(), "(", ")"), ",");
if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) {
{ column.setJavaType(GenConstants.TYPE_DOUBLE);
column.setJavaType(GenConstants.TYPE_BIGDECIMAL);
} }
// 如果是整形 // 如果是整形
else if (str != null && str.length == 1 && Integer.parseInt(str[0]) <= 10) else if (str != null && str.length == 1 && Integer.parseInt(str[0]) <= 10) {
{
column.setJavaType(GenConstants.TYPE_INTEGER); column.setJavaType(GenConstants.TYPE_INTEGER);
} }
// 长整形 // 长整形
else else {
{
column.setJavaType(GenConstants.TYPE_LONG); column.setJavaType(GenConstants.TYPE_LONG);
} }
} }
@ -80,58 +69,41 @@ public class GenUtils
column.setIsInsert(GenConstants.REQUIRE); column.setIsInsert(GenConstants.REQUIRE);
// 编辑字段 // 编辑字段
if (!arraysContains(GenConstants.COLUMNNAME_NOT_EDIT, columnName) && !column.isPk()) if (!arraysContains(GenConstants.COLUMNNAME_NOT_EDIT, columnName) && !column.isPk()) {
{
column.setIsEdit(GenConstants.REQUIRE); column.setIsEdit(GenConstants.REQUIRE);
} }
// 列表字段 // 列表字段
if (!arraysContains(GenConstants.COLUMNNAME_NOT_LIST, columnName) && !column.isPk()) if (!arraysContains(GenConstants.COLUMNNAME_NOT_LIST, columnName) && !column.isPk()) {
{
column.setIsList(GenConstants.REQUIRE); column.setIsList(GenConstants.REQUIRE);
} }
// 查询字段 // 查询字段
if (!arraysContains(GenConstants.COLUMNNAME_NOT_QUERY, columnName) && !column.isPk()) if (!arraysContains(GenConstants.COLUMNNAME_NOT_QUERY, columnName) && !column.isPk()) {
{
column.setIsQuery(GenConstants.REQUIRE); column.setIsQuery(GenConstants.REQUIRE);
} }
// 查询字段类型 // 查询字段类型
if (StringUtils.endsWithIgnoreCase(columnName, "name")) if (StringUtils.endsWithIgnoreCase(columnName, "name")) {
{
column.setQueryType(GenConstants.QUERY_LIKE); column.setQueryType(GenConstants.QUERY_LIKE);
} }
// 状态字段设置单选框 // 状态字段设置单选框
if (StringUtils.endsWithIgnoreCase(columnName, "status")) if (StringUtils.endsWithIgnoreCase(columnName, "status")) {
{
column.setHtmlType(GenConstants.HTML_RADIO); column.setHtmlType(GenConstants.HTML_RADIO);
} }
// 类型&性别字段设置下拉框 // 类型&性别字段设置下拉框
else if (StringUtils.endsWithIgnoreCase(columnName, "type") else if (StringUtils.endsWithIgnoreCase(columnName, "type")
|| StringUtils.endsWithIgnoreCase(columnName, "sex")) || StringUtils.endsWithIgnoreCase(columnName, "sex")) {
{
column.setHtmlType(GenConstants.HTML_SELECT); column.setHtmlType(GenConstants.HTML_SELECT);
} }
// 文件字段设置上传控件
else if (StringUtils.endsWithIgnoreCase(columnName, "file"))
{
column.setHtmlType(GenConstants.HTML_UPLOAD);
}
// 内容字段设置富文本控件
else if (StringUtils.endsWithIgnoreCase(columnName, "content"))
{
column.setHtmlType(GenConstants.HTML_SUMMERNOTE);
}
} }
/** /**
* 校验数组是否包含指定值 * 校验数组是否包含指定值
* *
* @param arr 数组 * @param arr 数组
* @param targetValue * @param targetValue
* @return 是否包含 * @return 是否包含
*/ */
public static boolean arraysContains(String[] arr, String targetValue) public static boolean arraysContains(String[] arr, String targetValue) {
{
return Arrays.asList(arr).contains(targetValue); return Arrays.asList(arr).contains(targetValue);
} }
@ -141,8 +113,7 @@ public class GenUtils
* @param packageName 包名 * @param packageName 包名
* @return 模块名 * @return 模块名
*/ */
public static String getModuleName(String packageName) public static String getModuleName(String packageName) {
{
int lastIndex = packageName.lastIndexOf("."); int lastIndex = packageName.lastIndexOf(".");
int nameLength = packageName.length(); int nameLength = packageName.length();
String moduleName = StringUtils.substring(packageName, lastIndex + 1, nameLength); String moduleName = StringUtils.substring(packageName, lastIndex + 1, nameLength);
@ -155,8 +126,7 @@ public class GenUtils
* @param tableName 表名 * @param tableName 表名
* @return 业务名 * @return 业务名
*/ */
public static String getBusinessName(String tableName) public static String getBusinessName(String tableName) {
{
int lastIndex = tableName.lastIndexOf("_"); int lastIndex = tableName.lastIndexOf("_");
int nameLength = tableName.length(); int nameLength = tableName.length();
String businessName = StringUtils.substring(tableName, lastIndex + 1, nameLength); String businessName = StringUtils.substring(tableName, lastIndex + 1, nameLength);
@ -169,47 +139,24 @@ public class GenUtils
* @param tableName 表名称 * @param tableName 表名称
* @return 类名 * @return 类名
*/ */
public static String convertClassName(String tableName) public static String convertClassName(String tableName) {
{
boolean autoRemovePre = GenConfig.getAutoRemovePre(); boolean autoRemovePre = GenConfig.getAutoRemovePre();
String tablePrefix = GenConfig.getTablePrefix(); String tablePrefix = GenConfig.getTablePrefix();
if (autoRemovePre && StringUtils.isNotEmpty(tablePrefix)) if (autoRemovePre && StringUtils.isNotEmpty(tablePrefix)) {
{
String[] searchList = StringUtils.split(tablePrefix, ","); String[] searchList = StringUtils.split(tablePrefix, ",");
tableName = replaceFirst(tableName, searchList); String[] replacementList = emptyList(searchList.length);
tableName = StringUtils.replaceEach(tableName, searchList, replacementList);
} }
return StringUtils.convertToCamelCase(tableName); return StringUtils.convertToCamelCase(tableName);
} }
/**
* 批量替换前缀
*
* @param replacementm 替换值
* @param searchList 替换列表
* @return
*/
public static String replaceFirst(String replacementm, String[] searchList)
{
String text = replacementm;
for (String searchString : searchList)
{
if (replacementm.startsWith(searchString))
{
text = replacementm.replaceFirst(searchString, "");
break;
}
}
return text;
}
/** /**
* 关键字替换 * 关键字替换
* *
* @param text 需要被替换的名字 * @param text 需要被替换的名字
* @return 替换后的名字 * @return 替换后的名字
*/ */
public static String replaceText(String text) public static String replaceText(String text) {
{
return RegExUtils.replaceAll(text, "(?:表|若依)", ""); return RegExUtils.replaceAll(text, "(?:表|若依)", "");
} }
@ -219,14 +166,10 @@ public class GenUtils
* @param columnType 列类型 * @param columnType 列类型
* @return 截取后的列类型 * @return 截取后的列类型
*/ */
public static String getDbType(String columnType) public static String getDbType(String columnType) {
{ if (StringUtils.indexOf(columnType, "(") > 0) {
if (StringUtils.indexOf(columnType, "(") > 0)
{
return StringUtils.substringBefore(columnType, "("); return StringUtils.substringBefore(columnType, "(");
} } else {
else
{
return columnType; return columnType;
} }
} }
@ -237,15 +180,11 @@ public class GenUtils
* @param columnType 列类型 * @param columnType 列类型
* @return 截取后的列类型 * @return 截取后的列类型
*/ */
public static Integer getColumnLength(String columnType) public static Integer getColumnLength(String columnType) {
{ if (StringUtils.indexOf(columnType, "(") > 0) {
if (StringUtils.indexOf(columnType, "(") > 0)
{
String length = StringUtils.substringBetween(columnType, "(", ")"); String length = StringUtils.substringBetween(columnType, "(", ")");
return Integer.valueOf(length); return Integer.valueOf(length);
} } else {
else
{
return 0; return 0;
} }
} }
@ -256,11 +195,9 @@ public class GenUtils
* @param length 长度 * @param length 长度
* @return 数组信息 * @return 数组信息
*/ */
public static String[] emptyList(int length) public static String[] emptyList(int length) {
{
String[] values = new String[length]; String[] values = new String[length];
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++) {
{
values[i] = StringUtils.EMPTY; values[i] = StringUtils.EMPTY;
} }
return values; return values;

View File

@ -1,9 +1,5 @@
package com.ruoyi.generator.util; package com.ruoyi.generator.util;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.apache.velocity.VelocityContext;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.GenConstants; import com.ruoyi.common.constant.GenConstants;
import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.DateUtils;
@ -11,28 +7,34 @@ import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.config.GenConfig; import com.ruoyi.generator.config.GenConfig;
import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn; import com.ruoyi.generator.domain.GenTableColumn;
import org.apache.velocity.VelocityContext;
public class VelocityUtils import java.util.ArrayList;
{ import java.util.HashSet;
/** 项目空间路径 */ import java.util.List;
public class VelocityUtils {
/**
* 项目空间路径
*/
private static final String PROJECT_PATH = "main/java"; private static final String PROJECT_PATH = "main/java";
/** mybatis空间路径 */ /**
* mybatis空间路径
*/
private static final String MYBATIS_PATH = "main/resources/mapper"; private static final String MYBATIS_PATH = "main/resources/mapper";
/** html空间路径 */ /**
* html空间路径
*/
private static final String TEMPLATES_PATH = "main/resources/templates"; private static final String TEMPLATES_PATH = "main/resources/templates";
/** 默认上级菜单,系统工具 */
private static final String DEFAULT_PARENT_MENU_ID = "3";
/** /**
* 设置模板变量信息 * 设置模板变量信息
* *
* @return 模板列表 * @return 模板列表
*/ */
public static VelocityContext prepareContext(GenTable genTable) public static VelocityContext prepareContext(GenTable genTable) {
{
String moduleName = genTable.getModuleName(); String moduleName = genTable.getModuleName();
String businessName = genTable.getBusinessName(); String businessName = genTable.getBusinessName();
String packageName = genTable.getPackageName(); String packageName = genTable.getPackageName();
@ -45,6 +47,7 @@ public class VelocityUtils
velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】"); velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】");
velocityContext.put("ClassName", genTable.getClassName()); velocityContext.put("ClassName", genTable.getClassName());
velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName())); velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName()));
velocityContext.put("classname", StringUtils.uncapitalize(genTable.getClassName()));
velocityContext.put("moduleName", genTable.getModuleName()); velocityContext.put("moduleName", genTable.getModuleName());
velocityContext.put("businessName", genTable.getBusinessName()); velocityContext.put("businessName", genTable.getBusinessName());
velocityContext.put("basePackage", getPackagePrefix(packageName)); velocityContext.put("basePackage", getPackagePrefix(packageName));
@ -52,32 +55,18 @@ public class VelocityUtils
velocityContext.put("author", genTable.getFunctionAuthor()); velocityContext.put("author", genTable.getFunctionAuthor());
velocityContext.put("datetime", DateUtils.getDate()); velocityContext.put("datetime", DateUtils.getDate());
velocityContext.put("pkColumn", genTable.getPkColumn()); velocityContext.put("pkColumn", genTable.getPkColumn());
velocityContext.put("importList", getImportList(genTable)); velocityContext.put("primaryKeyType", genTable.getPkColumn().getJavaType());
velocityContext.put("importList", getImportList(genTable.getColumns()));
velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName)); velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
velocityContext.put("columns", genTable.getColumns()); velocityContext.put("columns", genTable.getColumns());
velocityContext.put("table", genTable); velocityContext.put("table", genTable);
setMenuVelocityContext(velocityContext, genTable); if (GenConstants.TPL_TREE.equals(tplCategory)) {
if (GenConstants.TPL_TREE.equals(tplCategory))
{
setTreeVelocityContext(velocityContext, genTable); setTreeVelocityContext(velocityContext, genTable);
} }
if (GenConstants.TPL_SUB.equals(tplCategory))
{
setSubVelocityContext(velocityContext, genTable);
}
return velocityContext; return velocityContext;
} }
public static void setMenuVelocityContext(VelocityContext context, GenTable genTable) public static void setTreeVelocityContext(VelocityContext context, GenTable genTable) {
{
String options = genTable.getOptions();
JSONObject paramsObj = JSONObject.parseObject(options);
String parentMenuId = getParentMenuId(paramsObj);
context.put("parentMenuId", parentMenuId);
}
public static void setTreeVelocityContext(VelocityContext context, GenTable genTable)
{
String options = genTable.getOptions(); String options = genTable.getOptions();
JSONObject paramsObj = JSONObject.parseObject(options); JSONObject paramsObj = JSONObject.parseObject(options);
String treeCode = getTreecode(paramsObj); String treeCode = getTreecode(paramsObj);
@ -88,62 +77,32 @@ public class VelocityUtils
context.put("treeParentCode", treeParentCode); context.put("treeParentCode", treeParentCode);
context.put("treeName", treeName); context.put("treeName", treeName);
context.put("expandColumn", getExpandColumn(genTable)); context.put("expandColumn", getExpandColumn(genTable));
if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
{
context.put("tree_parent_code", paramsObj.getString(GenConstants.TREE_PARENT_CODE)); context.put("tree_parent_code", paramsObj.getString(GenConstants.TREE_PARENT_CODE));
} }
if (paramsObj.containsKey(GenConstants.TREE_NAME)) if (paramsObj.containsKey(GenConstants.TREE_NAME)) {
{
context.put("tree_name", paramsObj.getString(GenConstants.TREE_NAME)); context.put("tree_name", paramsObj.getString(GenConstants.TREE_NAME));
} }
} }
public static void setSubVelocityContext(VelocityContext context, GenTable genTable)
{
GenTable subTable = genTable.getSubTable();
String subTableName = genTable.getSubTableName();
String subTableFkName = genTable.getSubTableFkName();
String subClassName = genTable.getSubTable().getClassName();
String subTableFkClassName = StringUtils.convertToCamelCase(subTableFkName);
context.put("subTable", subTable);
context.put("subTableName", subTableName);
context.put("subTableFkName", subTableFkName);
context.put("subTableFkClassName", subTableFkClassName);
context.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName));
context.put("subClassName", subClassName);
context.put("subclassName", StringUtils.uncapitalize(subClassName));
context.put("subImportList", getImportList(genTable.getSubTable()));
}
/** /**
* 获取模板信息 * 获取模板信息
* *
* @return 模板列表 * @return 模板列表
*/ */
public static List<String> getTemplateList(String tplCategory) public static List<String> getTemplateList(String tplCategory) {
{
List<String> templates = new ArrayList<String>(); List<String> templates = new ArrayList<String>();
templates.add("vm/java/domain.java.vm"); templates.add("vm/java/domain.java.vm");
templates.add("vm/java/mapper.java.vm"); templates.add("vm/java/repository.java.vm");
templates.add("vm/java/service.java.vm"); templates.add("vm/java/service.java.vm");
templates.add("vm/java/serviceImpl.java.vm");
templates.add("vm/java/controller.java.vm"); templates.add("vm/java/controller.java.vm");
templates.add("vm/xml/mapper.xml.vm"); templates.add("vm/xml/mapper.xml.vm");
if (GenConstants.TPL_CRUD.equals(tplCategory)) if (GenConstants.TPL_CRUD.equals(tplCategory)) {
{
templates.add("vm/html/list.html.vm"); templates.add("vm/html/list.html.vm");
} } else if (GenConstants.TPL_TREE.equals(tplCategory)) {
else if (GenConstants.TPL_TREE.equals(tplCategory))
{
templates.add("vm/html/tree.html.vm"); templates.add("vm/html/tree.html.vm");
templates.add("vm/html/list-tree.html.vm"); templates.add("vm/html/list-tree.html.vm");
} }
else if (GenConstants.TPL_SUB.equals(tplCategory))
{
templates.add("vm/html/list.html.vm");
templates.add("vm/java/sub-domain.java.vm");
}
templates.add("vm/html/add.html.vm"); templates.add("vm/html/add.html.vm");
templates.add("vm/html/edit.html.vm"); templates.add("vm/html/edit.html.vm");
templates.add("vm/sql/sql.vm"); templates.add("vm/sql/sql.vm");
@ -153,8 +112,7 @@ public class VelocityUtils
/** /**
* 获取文件名 * 获取文件名
*/ */
public static String getFileName(String template, GenTable genTable) public static String getFileName(String template, GenTable genTable) {
{
// 文件名称 // 文件名称
String fileName = ""; String fileName = "";
// 包路径 // 包路径
@ -170,56 +128,31 @@ public class VelocityUtils
String mybatisPath = MYBATIS_PATH + "/" + moduleName; String mybatisPath = MYBATIS_PATH + "/" + moduleName;
String htmlPath = TEMPLATES_PATH + "/" + moduleName + "/" + businessName; String htmlPath = TEMPLATES_PATH + "/" + moduleName + "/" + businessName;
if (template.contains("domain.java.vm")) if (template.contains("domain.java.vm")) {
{ fileName = StringUtils.format("{}/entity/{}.java", javaPath, className);
fileName = StringUtils.format("{}/domain/{}.java", javaPath, className); } else if (template.contains("mapper.java.vm")) {
}
if (template.contains("sub-domain.java.vm") && StringUtils.equals(GenConstants.TPL_SUB, genTable.getTplCategory()))
{
fileName = StringUtils.format("{}/domain/{}.java", javaPath, genTable.getSubTable().getClassName());
}
else if (template.contains("mapper.java.vm"))
{
fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className); fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className);
} } else if (template.contains("repository.java.vm")) {
else if (template.contains("service.java.vm")) fileName = StringUtils.format("{}/repository/{}Repository.java", javaPath, className);
{ } else if (template.contains("service.java.vm")) {
fileName = StringUtils.format("{}/service/I{}Service.java", javaPath, className); fileName = StringUtils.format("{}/service/{}Service.java", javaPath, className);
} } else if (template.contains("serviceImpl.java.vm")) {
else if (template.contains("serviceImpl.java.vm"))
{
fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className); fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className);
} } else if (template.contains("controller.java.vm")) {
else if (template.contains("controller.java.vm"))
{
fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className); fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className);
} } else if (template.contains("mapper.xml.vm")) {
else if (template.contains("mapper.xml.vm"))
{
fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className); fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className);
} } else if (template.contains("list.html.vm")) {
else if (template.contains("list.html.vm"))
{
fileName = StringUtils.format("{}/{}.html", htmlPath, businessName); fileName = StringUtils.format("{}/{}.html", htmlPath, businessName);
} } else if (template.contains("list-tree.html.vm")) {
else if (template.contains("list-tree.html.vm"))
{
fileName = StringUtils.format("{}/{}.html", htmlPath, businessName); fileName = StringUtils.format("{}/{}.html", htmlPath, businessName);
} } else if (template.contains("tree.html.vm")) {
else if (template.contains("tree.html.vm"))
{
fileName = StringUtils.format("{}/tree.html", htmlPath); fileName = StringUtils.format("{}/tree.html", htmlPath);
} } else if (template.contains("add.html.vm")) {
else if (template.contains("add.html.vm"))
{
fileName = StringUtils.format("{}/add.html", htmlPath); fileName = StringUtils.format("{}/add.html", htmlPath);
} } else if (template.contains("edit.html.vm")) {
else if (template.contains("edit.html.vm"))
{
fileName = StringUtils.format("{}/edit.html", htmlPath); fileName = StringUtils.format("{}/edit.html", htmlPath);
} } else if (template.contains("sql.vm")) {
else if (template.contains("sql.vm"))
{
fileName = businessName + "Menu.sql"; fileName = businessName + "Menu.sql";
} }
return fileName; return fileName;
@ -230,8 +163,7 @@ public class VelocityUtils
* *
* @return 路径 * @return 路径
*/ */
public static String getProjectPath() public static String getProjectPath() {
{
String packageName = GenConfig.getPackageName(); String packageName = GenConfig.getPackageName();
StringBuffer projectPath = new StringBuffer(); StringBuffer projectPath = new StringBuffer();
projectPath.append("main/java/"); projectPath.append("main/java/");
@ -246,8 +178,7 @@ public class VelocityUtils
* @param packageName 包名称 * @param packageName 包名称
* @return 包前缀名称 * @return 包前缀名称
*/ */
public static String getPackagePrefix(String packageName) public static String getPackagePrefix(String packageName) {
{
int lastIndex = packageName.lastIndexOf("."); int lastIndex = packageName.lastIndexOf(".");
String basePackage = StringUtils.substring(packageName, 0, lastIndex); String basePackage = StringUtils.substring(packageName, 0, lastIndex);
return basePackage; return basePackage;
@ -256,26 +187,15 @@ public class VelocityUtils
/** /**
* 根据列类型获取导入包 * 根据列类型获取导入包
* *
* @param genTable 业务表对象 * @param columns 列集合
* @return 返回需要导入的包列表 * @return 返回需要导入的包列表
*/ */
public static HashSet<String> getImportList(GenTable genTable) public static HashSet<String> getImportList(List<GenTableColumn> columns) {
{
List<GenTableColumn> columns = genTable.getColumns();
GenTable subGenTable = genTable.getSubTable();
HashSet<String> importList = new HashSet<String>(); HashSet<String> importList = new HashSet<String>();
if (StringUtils.isNotNull(subGenTable)) for (GenTableColumn column : columns) {
{ if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) {
importList.add("java.util.List");
}
for (GenTableColumn column : columns)
{
if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType()))
{
importList.add("java.util.Date"); importList.add("java.util.Date");
} } else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) {
else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType()))
{
importList.add("java.math.BigDecimal"); importList.add("java.math.BigDecimal");
} }
} }
@ -285,73 +205,52 @@ public class VelocityUtils
/** /**
* 获取权限前缀 * 获取权限前缀
* *
* @param moduleName 模块名称 * @param moduleName 模块名称
* @param businessName 业务名称 * @param businessName 业务名称
* @return 返回权限前缀 * @return 返回权限前缀
*/ */
public static String getPermissionPrefix(String moduleName, String businessName) public static String getPermissionPrefix(String moduleName, String businessName) {
{
return StringUtils.format("{}:{}", moduleName, businessName); return StringUtils.format("{}:{}", moduleName, businessName);
}
/**
* 获取上级菜单ID字段
*
* @param options 生成其他选项
* @return 上级菜单ID字段
*/
public static String getParentMenuId(JSONObject paramsObj)
{
if (StringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID))
{
return paramsObj.getString(GenConstants.PARENT_MENU_ID);
}
return DEFAULT_PARENT_MENU_ID;
} }
/** /**
* 获取树编码 * 获取树编码
* *
* @param options 生成其他选项 * @param paramsObj 生成其他选项
* @return 树编码 * @return 树编码
*/ */
public static String getTreecode(JSONObject paramsObj) public static String getTreecode(JSONObject paramsObj) {
{ if (paramsObj.containsKey(GenConstants.TREE_CODE)) {
if (paramsObj.containsKey(GenConstants.TREE_CODE))
{
return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE)); return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE));
} }
return StringUtils.EMPTY; return "";
} }
/** /**
* 获取树父编码 * 获取树父编码
* *
* @param options 生成其他选项 * @param paramsObj 生成其他选项
* @return 树父编码 * @return 树父编码
*/ */
public static String getTreeParentCode(JSONObject paramsObj) public static String getTreeParentCode(JSONObject paramsObj) {
{ if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE))
{
return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE)); return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE));
} }
return StringUtils.EMPTY; return "";
} }
/** /**
* 获取树名称 * 获取树名称
* *
* @param options 生成其他选项 * @param paramsObj 生成其他选项
* @return 树名称 * @return 树名称
*/ */
public static String getTreeName(JSONObject paramsObj) public static String getTreeName(JSONObject paramsObj) {
{ if (paramsObj.containsKey(GenConstants.TREE_NAME)) {
if (paramsObj.containsKey(GenConstants.TREE_NAME))
{
return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME)); return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME));
} }
return StringUtils.EMPTY; return "";
} }
/** /**
@ -360,20 +259,16 @@ public class VelocityUtils
* @param genTable 业务表对象 * @param genTable 业务表对象
* @return 展开按钮列序号 * @return 展开按钮列序号
*/ */
public static int getExpandColumn(GenTable genTable) public static int getExpandColumn(GenTable genTable) {
{
String options = genTable.getOptions(); String options = genTable.getOptions();
JSONObject paramsObj = JSONObject.parseObject(options); JSONObject paramsObj = JSONObject.parseObject(options);
String treeName = paramsObj.getString(GenConstants.TREE_NAME); String treeName = paramsObj.getString(GenConstants.TREE_NAME);
int num = 0; int num = 0;
for (GenTableColumn column : genTable.getColumns()) for (GenTableColumn column : genTable.getColumns()) {
{ if (column.isList()) {
if (column.isList())
{
num++; num++;
String columnName = column.getColumnName(); String columnName = column.getColumnName();
if (columnName.equals(treeName)) if (columnName.equals(treeName)) {
{
break; break;
} }
} }

View File

@ -1,127 +0,0 @@
<?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.ruoyi.generator.mapper.GenTableColumnMapper">
<resultMap type="GenTableColumn" id="GenTableColumnResult">
<id property="columnId" column="column_id" />
<result property="tableId" column="table_id" />
<result property="columnName" column="column_name" />
<result property="columnComment" column="column_comment" />
<result property="columnType" column="column_type" />
<result property="javaType" column="java_type" />
<result property="javaField" column="java_field" />
<result property="isPk" column="is_pk" />
<result property="isIncrement" column="is_increment" />
<result property="isRequired" column="is_required" />
<result property="isInsert" column="is_insert" />
<result property="isEdit" column="is_edit" />
<result property="isList" column="is_list" />
<result property="isQuery" column="is_query" />
<result property="queryType" column="query_type" />
<result property="htmlType" column="html_type" />
<result property="dictType" column="dict_type" />
<result property="sort" column="sort" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
</resultMap>
<sql id="selectGenTableColumnVo">
select column_id, table_id, column_name, column_comment, column_type, java_type, java_field, is_pk, is_increment, is_required, is_insert, is_edit, is_list, is_query, query_type, html_type, dict_type, sort, create_by, create_time, update_by, update_time from gen_table_column
</sql>
<select id="selectGenTableColumnListByTableId" parameterType="GenTableColumn" resultMap="GenTableColumnResult">
<include refid="selectGenTableColumnVo"/>
where table_id = #{tableId}
order by sort
</select>
<select id="selectDbTableColumnsByName" parameterType="String" resultMap="GenTableColumnResult">
select column_name, (case when (is_nullable = 'no' <![CDATA[ && ]]> column_key != 'PRI') then '1' else null end) as is_required, (case when column_key = 'PRI' then '1' else '0' end) as is_pk, ordinal_position as sort, column_comment, (case when extra = 'auto_increment' then '1' else '0' end) as is_increment, column_type
from information_schema.columns where table_schema = (select database()) and table_name = (#{tableName})
order by ordinal_position
</select>
<insert id="insertGenTableColumn" parameterType="GenTableColumn" useGeneratedKeys="true" keyProperty="columnId">
insert into gen_table_column (
<if test="tableId != null and tableId != ''">table_id,</if>
<if test="columnName != null and columnName != ''">column_name,</if>
<if test="columnComment != null and columnComment != ''">column_comment,</if>
<if test="columnType != null and columnType != ''">column_type,</if>
<if test="javaType != null and javaType != ''">java_type,</if>
<if test="javaField != null and javaField != ''">java_field,</if>
<if test="isPk != null and isPk != ''">is_pk,</if>
<if test="isIncrement != null and isIncrement != ''">is_increment,</if>
<if test="isRequired != null and isRequired != ''">is_required,</if>
<if test="isInsert != null and isInsert != ''">is_insert,</if>
<if test="isEdit != null and isEdit != ''">is_edit,</if>
<if test="isList != null and isList != ''">is_list,</if>
<if test="isQuery != null and isQuery != ''">is_query,</if>
<if test="queryType != null and queryType != ''">query_type,</if>
<if test="htmlType != null and htmlType != ''">html_type,</if>
<if test="dictType != null and dictType != ''">dict_type,</if>
<if test="sort != null">sort,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
create_time
)values(
<if test="tableId != null and tableId != ''">#{tableId},</if>
<if test="columnName != null and columnName != ''">#{columnName},</if>
<if test="columnComment != null and columnComment != ''">#{columnComment},</if>
<if test="columnType != null and columnType != ''">#{columnType},</if>
<if test="javaType != null and javaType != ''">#{javaType},</if>
<if test="javaField != null and javaField != ''">#{javaField},</if>
<if test="isPk != null and isPk != ''">#{isPk},</if>
<if test="isIncrement != null and isIncrement != ''">#{isIncrement},</if>
<if test="isRequired != null and isRequired != ''">#{isRequired},</if>
<if test="isInsert != null and isInsert != ''">#{isInsert},</if>
<if test="isEdit != null and isEdit != ''">#{isEdit},</if>
<if test="isList != null and isList != ''">#{isList},</if>
<if test="isQuery != null and isQuery != ''">#{isQuery},</if>
<if test="queryType != null and queryType != ''">#{queryType},</if>
<if test="htmlType != null and htmlType != ''">#{htmlType},</if>
<if test="dictType != null and dictType != ''">#{dictType},</if>
<if test="sort != null">#{sort},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
sysdate()
)
</insert>
<update id="updateGenTableColumn" parameterType="GenTableColumn">
update gen_table_column
<set>
column_comment = #{columnComment},
java_type = #{javaType},
java_field = #{javaField},
is_insert = #{isInsert},
is_edit = #{isEdit},
is_list = #{isList},
is_query = #{isQuery},
is_required = #{isRequired},
query_type = #{queryType},
html_type = #{htmlType},
dict_type = #{dictType},
sort = #{sort},
update_by = #{updateBy},
update_time = sysdate()
</set>
where column_id = #{columnId}
</update>
<delete id="deleteGenTableColumnByIds" parameterType="Long">
delete from gen_table_column where table_id in
<foreach collection="array" item="tableId" open="(" separator="," close=")">
#{tableId}
</foreach>
</delete>
<delete id="deleteGenTableColumns">
delete from gen_table_column where column_id in
<foreach collection="list" item="item" open="(" separator="," close=")">
#{item.columnId}
</foreach>
</delete>
</mapper>

View File

@ -1,189 +0,0 @@
<?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.ruoyi.generator.mapper.GenTableMapper">
<resultMap type="GenTable" id="GenTableResult">
<id property="tableId" column="table_id" />
<result property="tableName" column="table_name" />
<result property="tableComment" column="table_comment" />
<result property="subTableName" column="sub_table_name" />
<result property="subTableFkName" column="sub_table_fk_name" />
<result property="className" column="class_name" />
<result property="tplCategory" column="tpl_category" />
<result property="packageName" column="package_name" />
<result property="moduleName" column="module_name" />
<result property="businessName" column="business_name" />
<result property="functionName" column="function_name" />
<result property="functionAuthor" column="function_author" />
<result property="genType" column="gen_type" />
<result property="genPath" column="gen_path" />
<result property="options" column="options" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="remark" column="remark" />
<collection property="columns" javaType="java.util.List" resultMap="GenTableColumnResult" />
</resultMap>
<resultMap type="GenTableColumn" id="GenTableColumnResult">
<id property="columnId" column="column_id" />
<result property="tableId" column="table_id" />
<result property="columnName" column="column_name" />
<result property="columnComment" column="column_comment" />
<result property="columnType" column="column_type" />
<result property="javaType" column="java_type" />
<result property="javaField" column="java_field" />
<result property="isPk" column="is_pk" />
<result property="isIncrement" column="is_increment" />
<result property="isRequired" column="is_required" />
<result property="isInsert" column="is_insert" />
<result property="isEdit" column="is_edit" />
<result property="isList" column="is_list" />
<result property="isQuery" column="is_query" />
<result property="queryType" column="query_type" />
<result property="htmlType" column="html_type" />
<result property="dictType" column="dict_type" />
<result property="sort" column="sort" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
</resultMap>
<sql id="selectGenTableVo">
select table_id, table_name, table_comment, sub_table_name, sub_table_fk_name, class_name, tpl_category, package_name, module_name, business_name, function_name, function_author, gen_type, gen_path, options, create_by, create_time, update_by, update_time, remark from gen_table
</sql>
<select id="selectGenTableList" parameterType="GenTable" resultMap="GenTableResult">
<include refid="selectGenTableVo"/>
<where>
<if test="tableName != null and tableName != ''">
AND lower(table_name) like lower(concat('%', #{tableName}, '%'))
</if>
<if test="tableComment != null and tableComment != ''">
AND lower(table_comment) like lower(concat('%', #{tableComment}, '%'))
</if>
</where>
</select>
<select id="selectDbTableList" parameterType="GenTable" resultMap="GenTableResult">
select table_name, table_comment, create_time, update_time from information_schema.tables
where table_schema = (select database())
AND table_name NOT LIKE 'qrtz_%' AND table_name NOT LIKE 'gen_%'
AND table_name NOT IN (select table_name from gen_table)
<if test="tableName != null and tableName != ''">
AND lower(table_name) like lower(concat('%', #{tableName}, '%'))
</if>
<if test="tableComment != null and tableComment != ''">
AND lower(table_comment) like lower(concat('%', #{tableComment}, '%'))
</if>
</select>
<select id="selectDbTableListByNames" resultMap="GenTableResult">
select table_name, table_comment, create_time, update_time from information_schema.tables
where table_name NOT LIKE 'qrtz_%' and table_name NOT LIKE 'gen_%' and table_schema = (select database())
and table_name in
<foreach collection="array" item="name" open="(" separator="," close=")">
#{name}
</foreach>
</select>
<select id="selectTableByName" parameterType="String" resultMap="GenTableResult">
select table_name, table_comment, create_time, update_time from information_schema.tables
where table_comment <![CDATA[ <> ]]> '' and table_schema = (select database())
and table_name = #{tableName}
</select>
<select id="selectGenTableById" parameterType="Long" resultMap="GenTableResult">
SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id
where t.table_id = #{tableId} order by c.sort
</select>
<select id="selectGenTableByName" parameterType="String" resultMap="GenTableResult">
SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id
where t.table_name = #{tableName} order by c.sort
</select>
<select id="selectGenTableAll" parameterType="String" resultMap="GenTableResult">
SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id
order by c.sort
</select>
<insert id="insertGenTable" parameterType="GenTable" useGeneratedKeys="true" keyProperty="tableId">
insert into gen_table (
<if test="tableName != null">table_name,</if>
<if test="tableComment != null and tableComment != ''">table_comment,</if>
<if test="className != null and className != ''">class_name,</if>
<if test="tplCategory != null and tplCategory != ''">tpl_category,</if>
<if test="packageName != null and packageName != ''">package_name,</if>
<if test="moduleName != null and moduleName != ''">module_name,</if>
<if test="businessName != null and businessName != ''">business_name,</if>
<if test="functionName != null and functionName != ''">function_name,</if>
<if test="functionAuthor != null and functionAuthor != ''">function_author,</if>
<if test="genType != null and genType != ''">gen_type,</if>
<if test="genPath != null and genPath != ''">gen_path,</if>
<if test="remark != null and remark != ''">remark,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
create_time
)values(
<if test="tableName != null">#{tableName},</if>
<if test="tableComment != null and tableComment != ''">#{tableComment},</if>
<if test="className != null and className != ''">#{className},</if>
<if test="tplCategory != null and tplCategory != ''">#{tplCategory},</if>
<if test="packageName != null and packageName != ''">#{packageName},</if>
<if test="moduleName != null and moduleName != ''">#{moduleName},</if>
<if test="businessName != null and businessName != ''">#{businessName},</if>
<if test="functionName != null and functionName != ''">#{functionName},</if>
<if test="functionAuthor != null and functionAuthor != ''">#{functionAuthor},</if>
<if test="genType != null and genType != ''">#{genType},</if>
<if test="genPath != null and genPath != ''">#{genPath},</if>
<if test="remark != null and remark != ''">#{remark},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
sysdate()
)
</insert>
<update id="updateGenTable" parameterType="GenTable">
update gen_table
<set>
<if test="tableName != null">table_name = #{tableName},</if>
<if test="tableComment != null and tableComment != ''">table_comment = #{tableComment},</if>
<if test="subTableName != null and subTableName != ''">sub_table_name = #{subTableName},</if>
<if test="subTableFkName != null and subTableFkName != ''">sub_table_fk_name = #{subTableFkName},</if>
<if test="className != null and className != ''">class_name = #{className},</if>
<if test="functionAuthor != null and functionAuthor != ''">function_author = #{functionAuthor},</if>
<if test="genType != null and genType != ''">gen_type = #{genType},</if>
<if test="genPath != null and genPath != ''">gen_path = #{genPath},</if>
<if test="tplCategory != null and tplCategory != ''">tpl_category = #{tplCategory},</if>
<if test="packageName != null and packageName != ''">package_name = #{packageName},</if>
<if test="moduleName != null and moduleName != ''">module_name = #{moduleName},</if>
<if test="businessName != null and businessName != ''">business_name = #{businessName},</if>
<if test="functionName != null and functionName != ''">function_name = #{functionName},</if>
<if test="options != null and options != ''">options = #{options},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
<if test="remark != null">remark = #{remark},</if>
update_time = sysdate()
</set>
where table_id = #{tableId}
</update>
<delete id="deleteGenTableByIds" parameterType="Long">
delete from gen_table where table_id in
<foreach collection="array" item="tableId" open="(" separator="," close=")">
#{tableId}
</foreach>
</delete>
</mapper>

View File

@ -1,17 +1,5 @@
package com.ruoyi.quartz.controller; package com.ruoyi.quartz.controller;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log; import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.AjaxResult;
@ -22,6 +10,16 @@ import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.quartz.domain.SysJob; import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService; import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.util.CronUtils; import com.ruoyi.quartz.util.CronUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/** /**
* 调度任务信息操作处理 * 调度任务信息操作处理
@ -30,8 +28,7 @@ import com.ruoyi.quartz.util.CronUtils;
*/ */
@Controller @Controller
@RequestMapping("/monitor/job") @RequestMapping("/monitor/job")
public class SysJobController extends BaseController public class SysJobController extends BaseController {
{
private String prefix = "monitor/job"; private String prefix = "monitor/job";
@Autowired @Autowired
@ -39,28 +36,23 @@ public class SysJobController extends BaseController
@RequiresPermissions("monitor:job:view") @RequiresPermissions("monitor:job:view")
@GetMapping() @GetMapping()
public String job() public String job() {
{
return prefix + "/job"; return prefix + "/job";
} }
@RequiresPermissions("monitor:job:list") @RequiresPermissions("monitor:job:list")
@PostMapping("/list") @PostMapping("/list")
@ResponseBody @ResponseBody
public TableDataInfo list(SysJob job) public TableDataInfo list(SysJob job) {
{ return getDataTable(jobService.selectJobList(job, getPageRequest()));
startPage();
List<SysJob> list = jobService.selectJobList(job);
return getDataTable(list);
} }
@Log(title = "定时任务", businessType = BusinessType.EXPORT) @Log(title = "定时任务", businessType = BusinessType.EXPORT)
@RequiresPermissions("monitor:job:export") @RequiresPermissions("monitor:job:export")
@PostMapping("/export") @PostMapping("/export")
@ResponseBody @ResponseBody
public AjaxResult export(SysJob job) public AjaxResult export(SysJob job) {
{ List<SysJob> list = jobService.selectJobList(job, Pageable.unpaged()).getContent();
List<SysJob> list = jobService.selectJobList(job);
ExcelUtil<SysJob> util = new ExcelUtil<SysJob>(SysJob.class); ExcelUtil<SysJob> util = new ExcelUtil<SysJob>(SysJob.class);
return util.exportExcel(list, "定时任务"); return util.exportExcel(list, "定时任务");
} }
@ -69,16 +61,14 @@ public class SysJobController extends BaseController
@RequiresPermissions("monitor:job:remove") @RequiresPermissions("monitor:job:remove")
@PostMapping("/remove") @PostMapping("/remove")
@ResponseBody @ResponseBody
public AjaxResult remove(String ids) throws SchedulerException public AjaxResult remove(String ids) throws SchedulerException {
{
jobService.deleteJobByIds(ids); jobService.deleteJobByIds(ids);
return success(); return success();
} }
@RequiresPermissions("monitor:job:detail") @RequiresPermissions("monitor:job:detail")
@GetMapping("/detail/{jobId}") @GetMapping("/detail/{jobId}")
public String detail(@PathVariable("jobId") Long jobId, ModelMap mmap) public String detail(@PathVariable("jobId") Long jobId, ModelMap mmap) {
{
mmap.put("name", "job"); mmap.put("name", "job");
mmap.put("job", jobService.selectJobById(jobId)); mmap.put("job", jobService.selectJobById(jobId));
return prefix + "/detail"; return prefix + "/detail";
@ -91,8 +81,7 @@ public class SysJobController extends BaseController
@RequiresPermissions("monitor:job:changeStatus") @RequiresPermissions("monitor:job:changeStatus")
@PostMapping("/changeStatus") @PostMapping("/changeStatus")
@ResponseBody @ResponseBody
public AjaxResult changeStatus(SysJob job) throws SchedulerException public AjaxResult changeStatus(SysJob job) throws SchedulerException {
{
SysJob newJob = jobService.selectJobById(job.getJobId()); SysJob newJob = jobService.selectJobById(job.getJobId());
newJob.setStatus(job.getStatus()); newJob.setStatus(job.getStatus());
return toAjax(jobService.changeStatus(newJob)); return toAjax(jobService.changeStatus(newJob));
@ -105,8 +94,7 @@ public class SysJobController extends BaseController
@RequiresPermissions("monitor:job:changeStatus") @RequiresPermissions("monitor:job:changeStatus")
@PostMapping("/run") @PostMapping("/run")
@ResponseBody @ResponseBody
public AjaxResult run(SysJob job) throws SchedulerException public AjaxResult run(SysJob job) throws SchedulerException {
{
jobService.run(job); jobService.run(job);
return success(); return success();
} }
@ -115,8 +103,7 @@ public class SysJobController extends BaseController
* 新增调度 * 新增调度
*/ */
@GetMapping("/add") @GetMapping("/add")
public String add() public String add() {
{
return prefix + "/add"; return prefix + "/add";
} }
@ -127,8 +114,7 @@ public class SysJobController extends BaseController
@RequiresPermissions("monitor:job:add") @RequiresPermissions("monitor:job:add")
@PostMapping("/add") @PostMapping("/add")
@ResponseBody @ResponseBody
public AjaxResult addSave(@Validated SysJob job) throws SchedulerException, TaskException public AjaxResult addSave(@Validated SysJob job) throws SchedulerException, TaskException {
{
if (!CronUtils.isValid(job.getCronExpression())) if (!CronUtils.isValid(job.getCronExpression()))
{ {
return AjaxResult.error("cron表达式不正确"); return AjaxResult.error("cron表达式不正确");
@ -140,8 +126,7 @@ public class SysJobController extends BaseController
* 修改调度 * 修改调度
*/ */
@GetMapping("/edit/{jobId}") @GetMapping("/edit/{jobId}")
public String edit(@PathVariable("jobId") Long jobId, ModelMap mmap) public String edit(@PathVariable("jobId") Long jobId, ModelMap mmap) {
{
mmap.put("job", jobService.selectJobById(jobId)); mmap.put("job", jobService.selectJobById(jobId));
return prefix + "/edit"; return prefix + "/edit";
} }
@ -153,8 +138,7 @@ public class SysJobController extends BaseController
@RequiresPermissions("monitor:job:edit") @RequiresPermissions("monitor:job:edit")
@PostMapping("/edit") @PostMapping("/edit")
@ResponseBody @ResponseBody
public AjaxResult editSave(@Validated SysJob job) throws SchedulerException, TaskException public AjaxResult editSave(@Validated SysJob job) throws SchedulerException, TaskException {
{
if (!CronUtils.isValid(job.getCronExpression())) if (!CronUtils.isValid(job.getCronExpression()))
{ {
return AjaxResult.error("cron表达式不正确"); return AjaxResult.error("cron表达式不正确");
@ -167,8 +151,7 @@ public class SysJobController extends BaseController
*/ */
@PostMapping("/checkCronExpressionIsValid") @PostMapping("/checkCronExpressionIsValid")
@ResponseBody @ResponseBody
public boolean checkCronExpressionIsValid(SysJob job) public boolean checkCronExpressionIsValid(SysJob job) {
{
return jobService.checkCronExpressionIsValid(job.getCronExpression()); return jobService.checkCronExpressionIsValid(job.getCronExpression());
} }
} }

View File

@ -1,16 +1,5 @@
package com.ruoyi.quartz.controller; package com.ruoyi.quartz.controller;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log; import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.AjaxResult;
@ -22,6 +11,14 @@ import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.domain.SysJobLog; import com.ruoyi.quartz.domain.SysJobLog;
import com.ruoyi.quartz.service.ISysJobLogService; import com.ruoyi.quartz.service.ISysJobLogService;
import com.ruoyi.quartz.service.ISysJobService; import com.ruoyi.quartz.service.ISysJobService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/** /**
* 调度日志操作处理 * 调度日志操作处理
@ -30,13 +27,11 @@ import com.ruoyi.quartz.service.ISysJobService;
*/ */
@Controller @Controller
@RequestMapping("/monitor/jobLog") @RequestMapping("/monitor/jobLog")
public class SysJobLogController extends BaseController public class SysJobLogController extends BaseController {
{
private String prefix = "monitor/job"; private String prefix = "monitor/job";
@Autowired @Autowired
private ISysJobService jobService; private ISysJobService jobService;
@Autowired @Autowired
private ISysJobLogService jobLogService; private ISysJobLogService jobLogService;
@ -55,20 +50,16 @@ public class SysJobLogController extends BaseController
@RequiresPermissions("monitor:job:list") @RequiresPermissions("monitor:job:list")
@PostMapping("/list") @PostMapping("/list")
@ResponseBody @ResponseBody
public TableDataInfo list(SysJobLog jobLog) public TableDataInfo list(SysJobLog jobLog) {
{ return getDataTable(jobLogService.selectJobLogList(jobLog, getPageRequest()));
startPage();
List<SysJobLog> list = jobLogService.selectJobLogList(jobLog);
return getDataTable(list);
} }
@Log(title = "调度日志", businessType = BusinessType.EXPORT) @Log(title = "调度日志", businessType = BusinessType.EXPORT)
@RequiresPermissions("monitor:job:export") @RequiresPermissions("monitor:job:export")
@PostMapping("/export") @PostMapping("/export")
@ResponseBody @ResponseBody
public AjaxResult export(SysJobLog jobLog) public AjaxResult export(SysJobLog jobLog) {
{ List<SysJobLog> list = jobLogService.selectJobLogList(jobLog, Pageable.unpaged()).getContent();
List<SysJobLog> list = jobLogService.selectJobLogList(jobLog);
ExcelUtil<SysJobLog> util = new ExcelUtil<SysJobLog>(SysJobLog.class); ExcelUtil<SysJobLog> util = new ExcelUtil<SysJobLog>(SysJobLog.class);
return util.exportExcel(list, "调度日志"); return util.exportExcel(list, "调度日志");
} }
@ -77,15 +68,13 @@ public class SysJobLogController extends BaseController
@RequiresPermissions("monitor:job:remove") @RequiresPermissions("monitor:job:remove")
@PostMapping("/remove") @PostMapping("/remove")
@ResponseBody @ResponseBody
public AjaxResult remove(String ids) public AjaxResult remove(String ids) {
{
return toAjax(jobLogService.deleteJobLogByIds(ids)); return toAjax(jobLogService.deleteJobLogByIds(ids));
} }
@RequiresPermissions("monitor:job:detail") @RequiresPermissions("monitor:job:detail")
@GetMapping("/detail/{jobLogId}") @GetMapping("/detail/{jobLogId}")
public String detail(@PathVariable("jobLogId") Long jobLogId, ModelMap mmap) public String detail(@PathVariable("jobLogId") Long jobLogId, ModelMap mmap) {
{
mmap.put("name", "jobLog"); mmap.put("name", "jobLog");
mmap.put("jobLog", jobLogService.selectJobLogById(jobLogId)); mmap.put("jobLog", jobLogService.selectJobLogById(jobLogId));
return prefix + "/detail"; return prefix + "/detail";
@ -95,8 +84,7 @@ public class SysJobLogController extends BaseController
@RequiresPermissions("monitor:job:remove") @RequiresPermissions("monitor:job:remove")
@PostMapping("/clean") @PostMapping("/clean")
@ResponseBody @ResponseBody
public AjaxResult clean() public AjaxResult clean() {
{
jobLogService.cleanJobLog(); jobLogService.cleanJobLog();
return success(); return success();
} }

View File

@ -1,22 +1,32 @@
package com.ruoyi.quartz.service.impl; package com.ruoyi.quartz.service.impl;
import java.util.List; import com.querydsl.core.types.ExpressionUtils;
import javax.annotation.PostConstruct; import com.querydsl.core.types.Predicate;
import com.ruoyi.common.base.BaseService;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quartz.domain.QSysJob;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.repository.SysJobRepository;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.util.CronUtils;
import com.ruoyi.quartz.util.ScheduleUtils;
import org.quartz.JobDataMap; import org.quartz.JobDataMap;
import org.quartz.JobKey; import org.quartz.JobKey;
import org.quartz.Scheduler; import org.quartz.Scheduler;
import org.quartz.SchedulerException; import org.quartz.SchedulerException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.core.text.Convert; import javax.annotation.PostConstruct;
import com.ruoyi.common.exception.job.TaskException; import java.util.ArrayList;
import com.ruoyi.quartz.domain.SysJob; import java.util.List;
import com.ruoyi.quartz.mapper.SysJobMapper;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.util.CronUtils;
import com.ruoyi.quartz.util.ScheduleUtils;
/** /**
* 定时任务调度信息 服务层 * 定时任务调度信息 服务层
@ -24,26 +34,21 @@ import com.ruoyi.quartz.util.ScheduleUtils;
* @author ruoyi * @author ruoyi
*/ */
@Service @Service
public class SysJobServiceImpl implements ISysJobService public class SysJobServiceImpl extends BaseService implements ISysJobService {
{
@Autowired @Autowired
private Scheduler scheduler; private Scheduler scheduler;
@Autowired @Autowired
private SysJobMapper jobMapper; private SysJobRepository sysJobRepository;
/** /**
* 项目启动时初始化定时器 * 项目启动时初始化定时器
主要是防止手动修改数据库导致未同步到定时任务处理不能手动修改数据库ID和任务组名否则会导致脏数据 * 主要是防止手动修改数据库导致未同步到定时任务处理不能手动修改数据库ID和任务组名否则会导致脏数据
*/ */
@PostConstruct @PostConstruct
public void init() throws SchedulerException, TaskException public void init() throws SchedulerException, TaskException {
{ List<SysJob> jobList = sysJobRepository.findAll();
scheduler.clear(); for (SysJob job : jobList) {
List<SysJob> jobList = jobMapper.selectJobAll(); updateSchedulerJob(job, job.getJobGroup());
for (SysJob job : jobList)
{
ScheduleUtils.createScheduleJob(scheduler, job);
} }
} }
@ -54,9 +59,26 @@ public class SysJobServiceImpl implements ISysJobService
* @return * @return
*/ */
@Override @Override
public List<SysJob> selectJobList(SysJob job) public Page<SysJob> selectJobList(SysJob job, Pageable pageable) {
{ return sysJobRepository.findAll(getPredicate(job), pageable);
return jobMapper.selectJobList(job); }
private Predicate getPredicate(SysJob job){
QSysJob qSysJob = QSysJob.sysJob;
List<Predicate> predicates = new ArrayList<>();
if(StringUtils.isNotEmpty(job.getJobName())){
predicates.add(buildLike(qSysJob.jobName, job.getJobName()));
}
if(StringUtils.isNotEmpty(job.getJobGroup())){
predicates.add(buildEqual(qSysJob.jobGroup, job.getJobGroup()));
}
if(StringUtils.isNotEmpty(job.getStatus())){
predicates.add(buildEqual(qSysJob.status, job.getStatus()));
}
if(StringUtils.isNotEmpty(job.getInvokeTarget())){
predicates.add(buildLike(qSysJob.invokeTarget, job.getInvokeTarget()));
}
return ExpressionUtils.allOf(predicates);
} }
/** /**
@ -66,9 +88,8 @@ public class SysJobServiceImpl implements ISysJobService
* @return 调度任务对象信息 * @return 调度任务对象信息
*/ */
@Override @Override
public SysJob selectJobById(Long jobId) public SysJob selectJobById(Long jobId) {
{ return sysJobRepository.findById(jobId).get();
return jobMapper.selectJobById(jobId);
} }
/** /**
@ -78,17 +99,13 @@ public class SysJobServiceImpl implements ISysJobService
*/ */
@Override @Override
@Transactional @Transactional
public int pauseJob(SysJob job) throws SchedulerException public int pauseJob(SysJob job) throws SchedulerException {
{
Long jobId = job.getJobId(); Long jobId = job.getJobId();
String jobGroup = job.getJobGroup(); String jobGroup = job.getJobGroup();
job.setStatus(ScheduleConstants.Status.PAUSE.getValue()); job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
int rows = jobMapper.updateJob(job); sysJobRepository.updateStatus(job.getStatus(), jobId);
if (rows > 0) scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
{ return 1;
scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
return rows;
} }
/** /**
@ -98,17 +115,13 @@ public class SysJobServiceImpl implements ISysJobService
*/ */
@Override @Override
@Transactional @Transactional
public int resumeJob(SysJob job) throws SchedulerException public int resumeJob(SysJob job) throws SchedulerException {
{
Long jobId = job.getJobId(); Long jobId = job.getJobId();
String jobGroup = job.getJobGroup(); String jobGroup = job.getJobGroup();
job.setStatus(ScheduleConstants.Status.NORMAL.getValue()); job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
int rows = jobMapper.updateJob(job); sysJobRepository.updateStatus(job.getStatus(), jobId);
if (rows > 0) scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
{ return 1;
scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
return rows;
} }
/** /**
@ -118,16 +131,12 @@ public class SysJobServiceImpl implements ISysJobService
*/ */
@Override @Override
@Transactional @Transactional
public int deleteJob(SysJob job) throws SchedulerException public int deleteJob(SysJob job) throws SchedulerException {
{
Long jobId = job.getJobId(); Long jobId = job.getJobId();
String jobGroup = job.getJobGroup(); String jobGroup = job.getJobGroup();
int rows = jobMapper.deleteJobById(jobId); sysJobRepository.deleteById(jobId);
if (rows > 0) scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
{ return 1;
scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
return rows;
} }
/** /**
@ -138,12 +147,10 @@ public class SysJobServiceImpl implements ISysJobService
*/ */
@Override @Override
@Transactional @Transactional
public void deleteJobByIds(String ids) throws SchedulerException public void deleteJobByIds(String ids) throws SchedulerException {
{
Long[] jobIds = Convert.toLongArray(ids); Long[] jobIds = Convert.toLongArray(ids);
for (Long jobId : jobIds) for (Long jobId : jobIds) {
{ SysJob job = selectJobById(jobId);
SysJob job = jobMapper.selectJobById(jobId);
deleteJob(job); deleteJob(job);
} }
} }
@ -155,16 +162,12 @@ public class SysJobServiceImpl implements ISysJobService
*/ */
@Override @Override
@Transactional @Transactional
public int changeStatus(SysJob job) throws SchedulerException public int changeStatus(SysJob job) throws SchedulerException {
{
int rows = 0; int rows = 0;
String status = job.getStatus(); String status = job.getStatus();
if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
{
rows = resumeJob(job); rows = resumeJob(job);
} } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
else if (ScheduleConstants.Status.PAUSE.getValue().equals(status))
{
rows = pauseJob(job); rows = pauseJob(job);
} }
return rows; return rows;
@ -177,14 +180,14 @@ public class SysJobServiceImpl implements ISysJobService
*/ */
@Override @Override
@Transactional @Transactional
public void run(SysJob job) throws SchedulerException public void run(SysJob job) throws SchedulerException {
{
Long jobId = job.getJobId(); Long jobId = job.getJobId();
SysJob tmpObj = selectJobById(job.getJobId()); String jobGroup = job.getJobGroup();
SysJob properties = selectJobById(job.getJobId());
// 参数 // 参数
JobDataMap dataMap = new JobDataMap(); JobDataMap dataMap = new JobDataMap();
dataMap.put(ScheduleConstants.TASK_PROPERTIES, tmpObj); dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, tmpObj.getJobGroup()), dataMap); scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap);
} }
/** /**
@ -194,15 +197,11 @@ public class SysJobServiceImpl implements ISysJobService
*/ */
@Override @Override
@Transactional @Transactional
public int insertJob(SysJob job) throws SchedulerException, TaskException public int insertJob(SysJob job) throws SchedulerException, TaskException {
{
job.setStatus(ScheduleConstants.Status.PAUSE.getValue()); job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
int rows = jobMapper.insertJob(job); sysJobRepository.save(job);
if (rows > 0) ScheduleUtils.createScheduleJob(scheduler, job);
{ return 1;
ScheduleUtils.createScheduleJob(scheduler, job);
}
return rows;
} }
/** /**
@ -212,30 +211,24 @@ public class SysJobServiceImpl implements ISysJobService
*/ */
@Override @Override
@Transactional @Transactional
public int updateJob(SysJob job) throws SchedulerException, TaskException public int updateJob(SysJob job) throws SchedulerException, TaskException {
{
SysJob properties = selectJobById(job.getJobId()); SysJob properties = selectJobById(job.getJobId());
int rows = jobMapper.updateJob(job); BeanUtils.copyProperties(job, properties);
if (rows > 0) updateSchedulerJob(job, properties.getJobGroup());
{ return 1;
updateSchedulerJob(job, properties.getJobGroup());
}
return rows;
} }
/** /**
* 更新任务 * 更新任务
* *
* @param job 任务对象 * @param job 任务对象
* @param jobGroup 任务组名 * @param jobGroup 任务组名
*/ */
public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {
{
Long jobId = job.getJobId(); Long jobId = job.getJobId();
// 判断是否存在 // 判断是否存在
JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup); JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
if (scheduler.checkExists(jobKey)) if (scheduler.checkExists(jobKey)) {
{
// 防止创建时存在数据问题 先移除然后在执行创建操作 // 防止创建时存在数据问题 先移除然后在执行创建操作
scheduler.deleteJob(jobKey); scheduler.deleteJob(jobKey);
} }
@ -249,8 +242,7 @@ public class SysJobServiceImpl implements ISysJobService
* @return 结果 * @return 结果
*/ */
@Override @Override
public boolean checkCronExpressionIsValid(String cronExpression) public boolean checkCronExpressionIsValid(String cronExpression) {
{
return CronUtils.isValid(cronExpression); return CronUtils.isValid(cronExpression);
} }
} }

View File

@ -19,6 +19,14 @@ import javax.validation.constraints.Size;
@Entity @Entity
@Table(name = "sys_dict_data") @Table(name = "sys_dict_data")
public class SysDictData extends BaseEntity { public class SysDictData extends BaseEntity {
public SysDictData() {
}
public SysDictData(Long id) {
this.dictCode = id;
}
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**

View File

@ -1,197 +1,222 @@
package com.ruoyi.system.domain; package com.ruoyi.system.domain;
import javax.validation.constraints.*; import com.ruoyi.common.annotation.DataScopes;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.annotation.Excel.ColumnType; import com.ruoyi.common.annotation.Excel.ColumnType;
import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/** /**
* 角色表 sys_role * 角色表 sys_role
* *
* @author ruoyi * @author ruoyi
*/ */
public class SysRole extends BaseEntity @Entity
{ @Table(name = "sys_role")
public class SysRole extends BaseEntity {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 角色ID */ /**
* 角色ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Excel(name = "角色序号", cellType = ColumnType.NUMERIC) @Excel(name = "角色序号", cellType = ColumnType.NUMERIC)
private Long roleId; private Long roleId;
/** 角色名称 */ /**
* 角色名称
*/
@Excel(name = "角色名称") @Excel(name = "角色名称")
private String roleName; private String roleName;
/** 角色权限 */ /**
* 角色权限
*/
@Excel(name = "角色权限") @Excel(name = "角色权限")
private String roleKey; private String roleKey;
/** 角色排序 */ /**
* 角色排序
*/
@Excel(name = "角色排序", cellType = ColumnType.NUMERIC) @Excel(name = "角色排序", cellType = ColumnType.NUMERIC)
private String roleSort; private Integer roleSort;
/** 数据范围1所有数据权限2自定义数据权限3本部门数据权限4本部门及以下数据权限 */ /**
* 数据范围1所有数据权限2自定义数据权限3本部门数据权限4本部门及以下数据权限
*/
@Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限") @Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限")
private String dataScope; @Enumerated(value = EnumType.ORDINAL)
private DataScopes dataScope;
/** 角色状态0正常 1停用 */ /**
* 角色状态0正常 1停用
*/
@Excel(name = "角色状态", readConverterExp = "0=正常,1=停用") @Excel(name = "角色状态", readConverterExp = "0=正常,1=停用")
private String status; private String status;
/** 删除标志0代表存在 2代表删除 */ /**
private String delFlag; * 删除标志0代表存在 2代表删除
*/
private String delFlag = BaseEntity.NOT_DELETED;
/** 用户是否存在此角色标识 默认不存在 */ /**
* 用户是否存在此角色标识 默认不存在
*/
@Transient
private boolean flag = false; private boolean flag = false;
/** 菜单组 */ @OneToMany(fetch = FetchType.LAZY)
private Long[] menuIds; @JoinTable(name = "sys_role_dept",
joinColumns = @JoinColumn(name = "roleId", referencedColumnName = "roleId"),
inverseJoinColumns = @JoinColumn(name = "deptId", referencedColumnName = "deptId"))
@org.hibernate.annotations.ForeignKey(name = "none")
private List<SysDept> depts;
/** 部门组(数据权限) */ @ManyToMany(fetch = FetchType.LAZY)
private Long[] deptIds; @JoinTable(name = "sys_role_menu",
joinColumns = @JoinColumn(name = "roleId", referencedColumnName = "roleId"),
inverseJoinColumns = @JoinColumn(name = "menuId", referencedColumnName = "menuId"))
@org.hibernate.annotations.ForeignKey(name = "none")
private Set<SysMenu> menus;
public SysRole() public SysRole() {
{
} }
public SysRole(Long roleId) public SysRole(Long roleId) {
{
this.roleId = roleId; this.roleId = roleId;
} }
public Long getRoleId() public Long getRoleId() {
{
return roleId; return roleId;
} }
public void setRoleId(Long roleId) public void setRoleId(Long roleId) {
{
this.roleId = roleId; this.roleId = roleId;
} }
public boolean isAdmin() public boolean isAdmin() {
{
return isAdmin(this.roleId); return isAdmin(this.roleId);
} }
public static boolean isAdmin(Long roleId) public static boolean isAdmin(Long roleId) {
{
return roleId != null && 1L == roleId; return roleId != null && 1L == roleId;
} }
public String getDataScope() public DataScopes getDataScope() {
{
return dataScope; return dataScope;
} }
public void setDataScope(String dataScope) public void setDataScope(DataScopes dataScope) {
{
this.dataScope = dataScope; this.dataScope = dataScope;
} }
@NotBlank(message = "角色名称不能为空") @NotBlank(message = "角色名称不能为空")
@Size(min = 0, max = 30, message = "角色名称长度不能超过30个字符") @Size(min = 0, max = 30, message = "角色名称长度不能超过30个字符")
public String getRoleName() public String getRoleName() {
{
return roleName; return roleName;
} }
public void setRoleName(String roleName) public void setRoleName(String roleName) {
{
this.roleName = roleName; this.roleName = roleName;
} }
@NotBlank(message = "权限字符不能为空") @NotBlank(message = "权限字符不能为空")
@Size(min = 0, max = 100, message = "权限字符长度不能超过100个字符") @Size(min = 0, max = 100, message = "权限字符长度不能超过100个字符")
public String getRoleKey() public String getRoleKey() {
{
return roleKey; return roleKey;
} }
public void setRoleKey(String roleKey) public void setRoleKey(String roleKey) {
{
this.roleKey = roleKey; this.roleKey = roleKey;
} }
@NotBlank(message = "显示顺序不能为空") @NotNull(message = "显示顺序不能为空")
public String getRoleSort() public Integer getRoleSort() {
{
return roleSort; return roleSort;
} }
public void setRoleSort(String roleSort) public void setRoleSort(Integer roleSort) {
{
this.roleSort = roleSort; this.roleSort = roleSort;
} }
public String getStatus() public String getStatus() {
{
return status; return status;
} }
public String getDelFlag() public String getDelFlag() {
{
return delFlag; return delFlag;
} }
public void setDelFlag(String delFlag) public void setDelFlag(String delFlag) {
{
this.delFlag = delFlag; this.delFlag = delFlag;
} }
public void setStatus(String status) public void setStatus(String status) {
{
this.status = status; this.status = status;
} }
public boolean isFlag() public boolean isFlag() {
{
return flag; return flag;
} }
public void setFlag(boolean flag) public void setFlag(boolean flag) {
{
this.flag = flag; this.flag = flag;
} }
public Long[] getMenuIds() public List<SysDept> getDepts() {
{ return depts;
return menuIds;
} }
public void setMenuIds(Long[] menuIds) public void setDepts(List<SysDept> depts) {
{ this.depts = depts;
this.menuIds = menuIds;
} }
public Long[] getDeptIds() public Set<SysMenu> getMenus() {
{ return menus;
return deptIds;
} }
public void setDeptIds(Long[] deptIds) public void setMenus(Set<SysMenu> menus) {
{ this.menus = menus;
this.deptIds = deptIds; }
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("roleId", getRoleId())
.append("roleName", getRoleName())
.append("roleKey", getRoleKey())
.append("roleSort", getRoleSort())
.append("dataScope", getDataScope())
.append("status", getStatus())
.append("delFlag", getDelFlag())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.toString();
} }
@Override @Override
public String toString() { public boolean equals(Object o) {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) if (this == o) return true;
.append("roleId", getRoleId()) if (o == null || getClass() != o.getClass()) return false;
.append("roleName", getRoleName()) SysRole sysRole = (SysRole) o;
.append("roleKey", getRoleKey()) return Objects.equals(roleId, sysRole.roleId);
.append("roleSort", getRoleSort()) }
.append("dataScope", getDataScope())
.append("status", getStatus()) @Override
.append("delFlag", getDelFlag()) public int hashCode() {
.append("createBy", getCreateBy()) return Objects.hash(roleId);
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.toString();
} }
} }

View File

@ -1,45 +0,0 @@
package com.ruoyi.system.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* 角色和部门关联 sys_role_dept
*
* @author ruoyi
*/
public class SysRoleDept {
/**
* 角色ID
*/
private Long roleId;
/**
* 部门ID
*/
private Long deptId;
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public Long getDeptId() {
return deptId;
}
public void setDeptId(Long deptId) {
this.deptId = deptId;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("roleId", getRoleId())
.append("deptId", getDeptId())
.toString();
}
}

View File

@ -1,366 +1,173 @@
package com.ruoyi.system.domain; package com.ruoyi.system.domain;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.*;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.annotation.Excel.ColumnType; import com.ruoyi.common.annotation.Excel.ColumnType;
import com.ruoyi.common.annotation.Excel.Type; import com.ruoyi.common.annotation.Excel.Type;
import com.ruoyi.common.annotation.Excels; import com.ruoyi.common.annotation.Excels;
import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.domain.BaseEntity;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.SelectBeforeUpdate;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/** /**
* 用户对象 sys_user * 用户对象 sys_user
* *
* @author ruoyi * @author ruoyi
*/ */
public class SysUser extends BaseEntity @Data
{ @Entity
@Table(name = "sys_user")
@DynamicUpdate
@SelectBeforeUpdate
public class SysUser extends BaseEntity {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 用户ID */ /**
* 用户ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Excel(name = "用户序号", cellType = ColumnType.NUMERIC, prompt = "用户编号") @Excel(name = "用户序号", cellType = ColumnType.NUMERIC, prompt = "用户编号")
private Long userId; private Long userId;
/** 部门ID */ /**
@Excel(name = "部门编号", type = Type.IMPORT) * 登录名称
private Long deptId; */
@NotBlank(message = "登录账号不能为空")
/** 部门父ID */ @Size(min = 0, max = 30, message = "登录账号长度不能超过30个字符")
private Long parentId;
/** 角色ID */
private Long roleId;
/** 登录名称 */
@Excel(name = "登录名称") @Excel(name = "登录名称")
private String loginName; private String loginName;
/** 用户名称 */ /**
* 用户名称
*/
@Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符")
@Excel(name = "用户名称") @Excel(name = "用户名称")
private String userName; private String userName;
/**
* 用户邮箱
*/
@Email(message = "邮箱格式不正确")
@Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符")
@Excel(name = "用户邮箱")
private String email;
/**
* 手机号码
*/
@Size(min = 0, max = 11, message = "手机号码长度不能超过11个字符")
@Excel(name = "手机号码")
private String phonenumber;
/**
* 用户性别
*/
@Excel(name = "用户性别", readConverterExp = "0=男,1=女,2=未知")
private String sex;
/**
* 用户头像
*/
private String avatar;
/**
* 密码
*/
private String password;
/**
* 盐加密
*/
private String salt;
/**
* 帐号状态0正常 1停用
*/
@Excel(name = "帐号状态", readConverterExp = "0=正常,1=停用")
private String status;
/**
* 删除标志0代表存在 2代表删除
*/
private String delFlag;
/**
* 最后登陆IP
*/
@Excel(name = "最后登陆IP", type = Type.EXPORT)
private String loginIp;
/**
* 最后登陆时间
*/
@Excel(name = "最后登陆时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Type.EXPORT)
private Date loginDate;
/** 用户类型 */ /** 用户类型 */
private String userType; private String userType;
/** 用户邮箱 */ /**
@Excel(name = "用户邮箱") * 部门对象
private String email; */
/** 手机号码 */
@Excel(name = "手机号码")
private String phonenumber;
/** 用户性别 */
@Excel(name = "用户性别", readConverterExp = "0=男,1=女,2=未知")
private String sex;
/** 用户头像 */
private String avatar;
/** 密码 */
private String password;
/** 盐加密 */
private String salt;
/** 帐号状态0正常 1停用 */
@Excel(name = "帐号状态", readConverterExp = "0=正常,1=停用")
private String status;
/** 删除标志0代表存在 2代表删除 */
private String delFlag;
/** 最后登陆IP */
@Excel(name = "最后登陆IP", type = Type.EXPORT)
private String loginIp;
/** 最后登陆时间 */
@Excel(name = "最后登陆时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Type.EXPORT)
private Date loginDate;
/** 部门对象 */
@Excels({ @Excels({
@Excel(name = "部门名称", targetAttr = "deptName", type = Type.EXPORT), @Excel(name = "部门名称", targetAttr = "deptName", type = Type.EXPORT),
@Excel(name = "部门负责人", targetAttr = "leader", type = Type.EXPORT) @Excel(name = "部门负责人", targetAttr = "leader", type = Type.EXPORT)
}) })
@ManyToOne
@JoinColumn(name = "dept_id", referencedColumnName = "deptId")
@ForeignKey(name = "none")
private SysDept dept; private SysDept dept;
private List<SysRole> roles; @ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "sys_user_role",
joinColumns = @JoinColumn(name = "userId", referencedColumnName = "userId"),
inverseJoinColumns = @JoinColumn(name = "roleId", referencedColumnName = "roleId"))
@ForeignKey(name = "none")
private Set<SysRole> roles = new HashSet<>();
/** 角色组 */ @ManyToMany(fetch = FetchType.LAZY)
private Long[] roleIds; @JoinTable(name = "sys_user_post",
inverseJoinColumns = @JoinColumn(name = "postId", referencedColumnName = "postId"),
joinColumns = @JoinColumn(name = "userId", referencedColumnName = "userId"))
@org.hibernate.annotations.ForeignKey(name = "none")
private Set<SysPost> posts = new HashSet<>();
/** 岗位组 */
private Long[] postIds;
public SysUser()
{ public SysUser() {
} }
public SysUser(Long userId) public SysUser(Long userId) {
{
this.userId = userId; this.userId = userId;
} }
public Long getUserId() @Transient
{ public boolean isAdmin() {
return userId;
}
public void setUserId(Long userId)
{
this.userId = userId;
}
public boolean isAdmin()
{
return isAdmin(this.userId); return isAdmin(this.userId);
} }
public static boolean isAdmin(Long userId) @Transient
{ public static boolean isAdmin(Long userId) {
return userId != null && 1L == userId; return userId != null && 1L == userId;
} }
public Long getDeptId() public SysDept getDept() {
{ if (dept == null) {
return deptId;
}
public void setDeptId(Long deptId)
{
this.deptId = deptId;
}
public Long getParentId()
{
return parentId;
}
public void setParentId(Long parentId)
{
this.parentId = parentId;
}
public Long getRoleId()
{
return roleId;
}
public void setRoleId(Long roleId)
{
this.roleId = roleId;
}
@NotBlank(message = "登录账号不能为空")
@Size(min = 0, max = 30, message = "登录账号长度不能超过30个字符")
public String getLoginName()
{
return loginName;
}
public void setLoginName(String loginName)
{
this.loginName = loginName;
}
@Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符")
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public String getUserType()
{
return userType;
}
public void setUserType(String userType)
{
this.userType = userType;
}
@Email(message = "邮箱格式不正确")
@Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符")
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
@Size(min = 0, max = 11, message = "手机号码长度不能超过11个字符")
public String getPhonenumber()
{
return phonenumber;
}
public void setPhonenumber(String phonenumber)
{
this.phonenumber = phonenumber;
}
public String getSex()
{
return sex;
}
public void setSex(String sex)
{
this.sex = sex;
}
public String getAvatar()
{
return avatar;
}
public void setAvatar(String avatar)
{
this.avatar = avatar;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getSalt()
{
return salt;
}
public void setSalt(String salt)
{
this.salt = salt;
}
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public String getDelFlag()
{
return delFlag;
}
public void setDelFlag(String delFlag)
{
this.delFlag = delFlag;
}
public String getLoginIp()
{
return loginIp;
}
public void setLoginIp(String loginIp)
{
this.loginIp = loginIp;
}
public Date getLoginDate()
{
return loginDate;
}
public void setLoginDate(Date loginDate)
{
this.loginDate = loginDate;
}
public SysDept getDept()
{
if (dept == null)
{
dept = new SysDept(); dept = new SysDept();
} }
return dept; return dept;
} }
public void setDept(SysDept dept)
{
this.dept = dept;
}
public List<SysRole> getRoles()
{
return roles;
}
public void setRoles(List<SysRole> roles)
{
this.roles = roles;
}
public Long[] getRoleIds()
{
return roleIds;
}
public void setRoleIds(Long[] roleIds)
{
this.roleIds = roleIds;
}
public Long[] getPostIds()
{
return postIds;
}
public void setPostIds(Long[] postIds)
{
this.postIds = postIds;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("userId", getUserId())
.append("deptId", getDeptId())
.append("loginName", getLoginName())
.append("userName", getUserName())
.append("userType", getUserType())
.append("email", getEmail())
.append("phonenumber", getPhonenumber())
.append("sex", getSex())
.append("avatar", getAvatar())
.append("password", getPassword())
.append("salt", getSalt())
.append("status", getStatus())
.append("delFlag", getDelFlag())
.append("loginIp", getLoginIp())
.append("loginDate", getLoginDate())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.append("dept", getDept())
.append("roles", getRoles())
.toString();
}
} }

View File

@ -1,117 +0,0 @@
package com.ruoyi.system.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.ruoyi.system.domain.SysDept;
/**
* 部门管理 数据层
*
* @author ruoyi
*/
public interface SysDeptMapper
{
/**
* 查询部门人数
*
* @param dept 部门信息
* @return 结果
*/
public int selectDeptCount(SysDept dept);
/**
* 查询部门是否存在用户
*
* @param deptId 部门ID
* @return 结果
*/
public int checkDeptExistUser(Long deptId);
/**
* 查询部门管理数据
*
* @param dept 部门信息
* @return 部门信息集合
*/
public List<SysDept> selectDeptList(SysDept dept);
/**
* 删除部门管理信息
*
* @param deptId 部门ID
* @return 结果
*/
public int deleteDeptById(Long deptId);
/**
* 新增部门信息
*
* @param dept 部门信息
* @return 结果
*/
public int insertDept(SysDept dept);
/**
* 修改部门信息
*
* @param dept 部门信息
* @return 结果
*/
public int updateDept(SysDept dept);
/**
* 修改子元素关系
*
* @param depts 子元素
* @return 结果
*/
public int updateDeptChildren(@Param("depts") List<SysDept> depts);
/**
* 根据部门ID查询信息
*
* @param deptId 部门ID
* @return 部门信息
*/
public SysDept selectDeptById(Long deptId);
/**
* 校验部门名称是否唯一
*
* @param deptName 部门名称
* @param parentId 父部门ID
* @return 结果
*/
public SysDept checkDeptNameUnique(@Param("deptName") String deptName, @Param("parentId") Long parentId);
/**
* 根据角色ID查询部门
*
* @param roleId 角色ID
* @return 部门列表
*/
public List<String> selectRoleDeptTree(Long roleId);
/**
* 修改所在部门的父级部门状态
*
* @param dept 部门
*/
public void updateDeptStatus(SysDept dept);
/**
* 根据ID查询所有子部门
*
* @param deptId 部门ID
* @return 部门列表
*/
public List<SysDept> selectChildrenDeptById(Long deptId);
/**
* 根据ID查询所有子部门正常状态
*
* @param deptId 部门ID
* @return 子部门数
*/
public int selectNormalChildrenDeptById(Long deptId);
}

View File

@ -1,70 +0,0 @@
package com.ruoyi.system.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.ruoyi.system.domain.SysUserRole;
/**
* 用户与角色关联表 数据层
*
* @author ruoyi
*/
public interface SysUserRoleMapper
{
/**
* 通过用户ID查询用户和角色关联
*
* @param userId 用户ID
* @return 用户和角色关联列表
*/
public List<SysUserRole> selectUserRoleByUserId(Long userId);
/**
* 通过用户ID删除用户和角色关联
*
* @param userId 用户ID
* @return 结果
*/
public int deleteUserRoleByUserId(Long userId);
/**
* 批量删除用户和角色关联
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteUserRole(Long[] ids);
/**
* 通过角色ID查询角色使用数量
*
* @param roleId 角色ID
* @return 结果
*/
public int countUserRoleByRoleId(Long roleId);
/**
* 批量新增用户角色信息
*
* @param userRoleList 用户角色列表
* @return 结果
*/
public int batchUserRole(List<SysUserRole> userRoleList);
/**
* 删除用户和角色关联信息
*
* @param userRole 用户和角色关联信息
* @return 结果
*/
public int deleteUserRoleInfo(SysUserRole userRole);
/**
* 批量取消授权用户角色
*
* @param roleId 角色ID
* @param userIds 需要删除的用户数据ID
* @return 结果
*/
public int deleteUserRoleInfos(@Param("roleId") Long roleId, @Param("userIds") Long[] userIds);
}

View File

@ -1,15 +1,17 @@
package com.ruoyi.system.service; package com.ruoyi.system.service;
import java.util.List; import java.util.List;
import com.ruoyi.system.domain.SysConfig; import com.ruoyi.system.domain.SysConfig;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
/** /**
* 参数配置 服务层 * 参数配置 服务层
* *
* @author ruoyi * @author ruoyi
*/ */
public interface ISysConfigService public interface ISysConfigService {
{
/** /**
* 查询参数配置信息 * 查询参数配置信息
* *
@ -32,7 +34,7 @@ public interface ISysConfigService
* @param config 参数配置信息 * @param config 参数配置信息
* @return 参数配置集合 * @return 参数配置集合
*/ */
public List<SysConfig> selectConfigList(SysConfig config); public Page<SysConfig> selectConfigList(SysConfig config, Pageable pageable);
/** /**
* 新增参数配置 * 新增参数配置
@ -58,11 +60,6 @@ public interface ISysConfigService
*/ */
public int deleteConfigByIds(String ids); public int deleteConfigByIds(String ids);
/**
* 清空缓存数据
*/
public void clearCache();
/** /**
* 校验参数键名是否唯一 * 校验参数键名是否唯一
* *
@ -70,4 +67,6 @@ public interface ISysConfigService
* @return 结果 * @return 结果
*/ */
public String checkConfigKeyUnique(SysConfig config); public String checkConfigKeyUnique(SysConfig config);
void clearCache();
} }

View File

@ -1,24 +1,26 @@
package com.ruoyi.system.service; package com.ruoyi.system.service;
import java.util.List;
import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysRole;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
/** /**
* 部门管理 服务层 * 部门管理 服务层
* *
* @author ruoyi * @author ruoyi
*/ */
public interface ISysDeptService public interface ISysDeptService {
{
/** /**
* 查询部门管理数据 * 查询部门管理数据
* *
* @param dept 部门信息 * @param dept 部门信息
* @return 部门信息集合 * @return 部门信息集合
*/ */
public List<SysDept> selectDeptList(SysDept dept); public Page<SysDept> selectDeptList(SysDept dept, Pageable pageable);
/** /**
* 查询部门管理树 * 查询部门管理树
@ -28,14 +30,6 @@ public interface ISysDeptService
*/ */
public List<Ztree> selectDeptTree(SysDept dept); public List<Ztree> selectDeptTree(SysDept dept);
/**
* 查询部门管理树排除下级
*
* @param dept 部门信息
* @return 所有部门信息
*/
public List<Ztree> selectDeptTreeExcludeChild(SysDept dept);
/** /**
* 根据角色ID查询菜单 * 根据角色ID查询菜单
* *
@ -45,12 +39,12 @@ public interface ISysDeptService
public List<Ztree> roleDeptTreeData(SysRole role); public List<Ztree> roleDeptTreeData(SysRole role);
/** /**
* 查询部门 * 查询下级部门数
* *
* @param parentId 部门ID * @param deptId 部门ID
* @return 结果 * @return 结果
*/ */
public int selectDeptCount(Long parentId); public int countChildren(Long deptId);
/** /**
* 查询部门是否存在用户 * 查询部门是否存在用户
@ -66,7 +60,7 @@ public interface ISysDeptService
* @param deptId 部门ID * @param deptId 部门ID
* @return 结果 * @return 结果
*/ */
public int deleteDeptById(Long deptId); public void deleteDeptById(Long deptId);
/** /**
* 新增保存部门信息 * 新增保存部门信息
@ -74,7 +68,7 @@ public interface ISysDeptService
* @param dept 部门信息 * @param dept 部门信息
* @return 结果 * @return 结果
*/ */
public int insertDept(SysDept dept); public SysDept insertDept(SysDept dept);
/** /**
* 修改保存部门信息 * 修改保存部门信息
@ -82,7 +76,7 @@ public interface ISysDeptService
* @param dept 部门信息 * @param dept 部门信息
* @return 结果 * @return 结果
*/ */
public int updateDept(SysDept dept); public SysDept updateDept(SysDept dept);
/** /**
* 根据部门ID查询信息 * 根据部门ID查询信息
@ -92,14 +86,6 @@ public interface ISysDeptService
*/ */
public SysDept selectDeptById(Long deptId); public SysDept selectDeptById(Long deptId);
/**
* 根据ID查询所有子部门正常状态
*
* @param deptId 部门ID
* @return 子部门数
*/
public int selectNormalChildrenDeptById(Long deptId);
/** /**
* 校验部门名称是否唯一 * 校验部门名称是否唯一
* *

View File

@ -1,27 +1,38 @@
package com.ruoyi.system.service; package com.ruoyi.system.service;
import java.util.List;
import com.ruoyi.system.domain.SysDictData; import com.ruoyi.system.domain.SysDictData;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
/** /**
* 字典 业务层 * 字典 业务层
* *
* @author ruoyi * @author ruoyi
*/ */
public interface ISysDictDataService public interface ISysDictDataService {
{
/** /**
* 根据条件分页查询字典数据 * 根据条件分页查询字典数据
* *
* @param dictData 字典数据信息 * @param dictData 字典数据信息
* @return 字典数据集合信息 * @return 字典数据集合信息
*/ */
public List<SysDictData> selectDictDataList(SysDictData dictData); public Page<SysDictData> selectDictDataList(SysDictData dictData, Pageable pageable);
/**
* 根据字典类型查询字典数据
*
* @param dictType 字典类型
* @return 字典数据集合信息
*/
public List<SysDictData> selectDictDataByType(String dictType);
/** /**
* 根据字典类型和字典键值查询字典数据信息 * 根据字典类型和字典键值查询字典数据信息
* *
* @param dictType 字典类型 * @param dictType 字典类型
* @param dictValue 字典键值 * @param dictValue 字典键值
* @return 字典标签 * @return 字典标签
*/ */
@ -35,6 +46,14 @@ public interface ISysDictDataService
*/ */
public SysDictData selectDictDataById(Long dictCode); public SysDictData selectDictDataById(Long dictCode);
/**
* 通过字典ID删除字典数据信息
*
* @param dictCode 字典数据ID
* @return 结果
*/
public int deleteDictDataById(Long dictCode);
/** /**
* 批量删除字典数据 * 批量删除字典数据
* *

View File

@ -1,24 +1,25 @@
package com.ruoyi.system.service; package com.ruoyi.system.service;
import java.util.List;
import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.domain.SysDictType; import com.ruoyi.system.domain.SysDictType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
/** /**
* 字典 业务层 * 字典 业务层
* *
* @author ruoyi * @author ruoyi
*/ */
public interface ISysDictTypeService public interface ISysDictTypeService {
{
/** /**
* 根据条件分页查询字典类型 * 根据条件分页查询字典类型
* *
* @param dictType 字典类型信息 * @param dictType 字典类型信息
* @return 字典类型集合信息 * @return 字典类型集合信息
*/ */
public List<SysDictType> selectDictTypeList(SysDictType dictType); public Page<SysDictType> selectDictTypeList(SysDictType dictType, Pageable pageable);
/** /**
* 根据所有字典类型 * 根据所有字典类型
@ -27,14 +28,6 @@ public interface ISysDictTypeService
*/ */
public List<SysDictType> selectDictTypeAll(); public List<SysDictType> selectDictTypeAll();
/**
* 根据字典类型查询字典数据
*
* @param dictType 字典类型
* @return 字典数据集合信息
*/
public List<SysDictData> selectDictDataByType(String dictType);
/** /**
* 根据字典类型ID查询信息 * 根据字典类型ID查询信息
* *
@ -51,6 +44,14 @@ public interface ISysDictTypeService
*/ */
public SysDictType selectDictTypeByType(String dictType); public SysDictType selectDictTypeByType(String dictType);
/**
* 通过字典ID删除字典信息
*
* @param dictId 字典ID
* @return 结果
*/
public int deleteDictTypeById(Long dictId);
/** /**
* 批量删除字典类型 * 批量删除字典类型
* *
@ -58,12 +59,7 @@ public interface ISysDictTypeService
* @return 结果 * @return 结果
* @throws Exception 异常 * @throws Exception 异常
*/ */
public int deleteDictTypeByIds(String ids); public int deleteDictTypeByIds(String ids) throws Exception;
/**
* 清空缓存数据
*/
public void clearCache();
/** /**
* 新增保存字典类型信息 * 新增保存字典类型信息
@ -96,4 +92,6 @@ public interface ISysDictTypeService
* @return 所有字典类型 * @return 所有字典类型
*/ */
public List<Ztree> selectDictTree(SysDictType dictType); public List<Ztree> selectDictTree(SysDictType dictType);
void clearCache();
} }

View File

@ -1,31 +1,36 @@
package com.ruoyi.system.service; package com.ruoyi.system.service;
import java.util.List; import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.SysUserRole; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Set;
/** /**
* 用户 业务层 * 用户 业务层
* *
* @author ruoyi * @author ruoyi
*/ */
public interface ISysUserService public interface ISysUserService {
{
/** /**
* 根据条件分页查询用户列表 * 根据条件分页查询用户列表
* *
* @param user 用户信息 * @param user 用户信息
* @param pageRequest
* @return 用户信息集合信息 * @return 用户信息集合信息
*/ */
public List<SysUser> selectUserList(SysUser user); public Page<SysUser> selectUserList(SysUser user, Pageable pageRequest);
/** /**
* 根据条件分页查询已分配用户角色列表 * 根据条件分页查询已分配用户角色列表
* *
* @param user 用户信息 * @param user 用户信息
* @param pageRequest
* @return 用户信息集合信息 * @return 用户信息集合信息
*/ */
public List<SysUser> selectAllocatedList(SysUser user); public Page<SysUser> selectAllocatedList(SysUser user, Pageable pageRequest);
/** /**
* 根据条件分页查询未分配用户角色列表 * 根据条件分页查询未分配用户角色列表
@ -33,7 +38,7 @@ public interface ISysUserService
* @param user 用户信息 * @param user 用户信息
* @return 用户信息集合信息 * @return 用户信息集合信息
*/ */
public List<SysUser> selectUnallocatedList(SysUser user); public Page<SysUser> selectUnallocatedList(SysUser user, Pageable pageable);
/** /**
* 通过用户名查询用户 * 通过用户名查询用户
@ -67,13 +72,7 @@ public interface ISysUserService
*/ */
public SysUser selectUserById(Long userId); public SysUser selectUserById(Long userId);
/** public SysUser selectUserWithRolesAndPostsById(Long userId);
* 通过用户ID查询用户和角色关联
*
* @param userId 用户ID
* @return 用户和角色关联列表
*/
public List<SysUserRole> selectUserRoleByUserId(Long userId);
/** /**
* 通过用户ID删除用户 * 通过用户ID删除用户
@ -98,15 +97,7 @@ public interface ISysUserService
* @param user 用户信息 * @param user 用户信息
* @return 结果 * @return 结果
*/ */
public int insertUser(SysUser user); public SysUser insertUser(SysUser user);
/**
* 注册用户信息
*
* @param user 用户信息
* @return 结果
*/
public boolean registerUser(SysUser user);
/** /**
* 保存用户信息 * 保存用户信息
@ -114,7 +105,7 @@ public interface ISysUserService
* @param user 用户信息 * @param user 用户信息
* @return 结果 * @return 结果
*/ */
public int updateUser(SysUser user); public SysUser updateUser(SysUser user);
/** /**
* 修改用户详细信息 * 修改用户详细信息
@ -122,15 +113,7 @@ public interface ISysUserService
* @param user 用户信息 * @param user 用户信息
* @return 结果 * @return 结果
*/ */
public int updateUserInfo(SysUser user); public SysUser updateUserInfo(SysUser user);
/**
* 用户授权角色
*
* @param userId 用户ID
* @param roleIds 角色组
*/
public void insertUserAuth(Long userId, Long[] roleIds);
/** /**
* 修改用户密码信息 * 修改用户密码信息
@ -138,7 +121,7 @@ public interface ISysUserService
* @param user 用户信息 * @param user 用户信息
* @return 结果 * @return 结果
*/ */
public int resetUserPwd(SysUser user); public SysUser resetUserPwd(SysUser user);
/** /**
* 校验用户名称是否唯一 * 校验用户名称是否唯一
@ -171,28 +154,12 @@ public interface ISysUserService
*/ */
public void checkUserAllowed(SysUser user); public void checkUserAllowed(SysUser user);
/**
* 根据用户ID查询用户所属角色组
*
* @param userId 用户ID
* @return 结果
*/
public String selectUserRoleGroup(Long userId);
/**
* 根据用户ID查询用户所属岗位组
*
* @param userId 用户ID
* @return 结果
*/
public String selectUserPostGroup(Long userId);
/** /**
* 导入用户数据 * 导入用户数据
* *
* @param userList 用户数据列表 * @param userList 用户数据列表
* @param isUpdateSupport 是否更新支持如果已存在则进行更新数据 * @param isUpdateSupport 是否更新支持如果已存在则进行更新数据
* @param operName 操作用户 * @param operName 操作用户
* @return 结果 * @return 结果
*/ */
public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName); public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName);
@ -203,5 +170,17 @@ public interface ISysUserService
* @param user 用户信息 * @param user 用户信息
* @return 结果 * @return 结果
*/ */
public int changeStatus(SysUser user); public void changeStatus(SysUser user);
Set<SysDept> getUserRoleDepts(Long userId);
/**
* 注册用户信息
*
* @param user 用户信息
* @return 结果
*/
public SysUser registerUser(SysUser user);
void insertUserAuth(Long userId, Long[] roleIds);
} }

View File

@ -1,18 +1,25 @@
package com.ruoyi.system.service.impl; package com.ruoyi.system.service.impl;
import java.util.List; import com.querydsl.core.types.ExpressionUtils;
import javax.annotation.PostConstruct; import com.querydsl.core.types.Predicate;
import org.springframework.beans.factory.annotation.Autowired; import com.ruoyi.common.base.BaseService;
import org.springframework.stereotype.Service;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.QSysConfig;
import com.ruoyi.system.domain.SysConfig; import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper; import com.ruoyi.system.repository.SysConfigRepository;
import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/** /**
* 参数配置 服务层实现 * 参数配置 服务层实现
@ -20,23 +27,9 @@ import com.ruoyi.system.service.ISysConfigService;
* @author ruoyi * @author ruoyi
*/ */
@Service @Service
public class SysConfigServiceImpl implements ISysConfigService public class SysConfigServiceImpl extends BaseService implements ISysConfigService {
{
@Autowired @Autowired
private SysConfigMapper configMapper; private SysConfigRepository sysConfigRepository;
/**
* 项目启动时初始化参数到缓存
*/
@PostConstruct
public void init()
{
List<SysConfig> configsList = configMapper.selectConfigList(new SysConfig());
for (SysConfig config : configsList)
{
CacheUtils.put(getCacheName(), getCacheKey(config.getConfigKey()), config.getConfigValue());
}
}
/** /**
* 查询参数配置信息 * 查询参数配置信息
@ -45,11 +38,8 @@ public class SysConfigServiceImpl implements ISysConfigService
* @return 参数配置信息 * @return 参数配置信息
*/ */
@Override @Override
public SysConfig selectConfigById(Long configId) public SysConfig selectConfigById(Long configId) {
{ return sysConfigRepository.findById(configId).get();
SysConfig config = new SysConfig();
config.setConfigId(configId);
return configMapper.selectConfig(config);
} }
/** /**
@ -59,22 +49,9 @@ public class SysConfigServiceImpl implements ISysConfigService
* @return 参数键值 * @return 参数键值
*/ */
@Override @Override
public String selectConfigByKey(String configKey) public String selectConfigByKey(String configKey) {
{ SysConfig retConfig = sysConfigRepository.findFirstByConfigKey(configKey);
String configValue = Convert.toStr(CacheUtils.get(getCacheName(), getCacheKey(configKey))); return StringUtils.isNotNull(retConfig) ? retConfig.getConfigValue() : "";
if (StringUtils.isNotEmpty(configValue))
{
return configValue;
}
SysConfig config = new SysConfig();
config.setConfigKey(configKey);
SysConfig retConfig = configMapper.selectConfig(config);
if (StringUtils.isNotNull(retConfig))
{
CacheUtils.put(getCacheName(), getCacheKey(configKey), retConfig.getConfigValue());
return retConfig.getConfigValue();
}
return StringUtils.EMPTY;
} }
/** /**
@ -84,9 +61,29 @@ public class SysConfigServiceImpl implements ISysConfigService
* @return 参数配置集合 * @return 参数配置集合
*/ */
@Override @Override
public List<SysConfig> selectConfigList(SysConfig config) public Page<SysConfig> selectConfigList(SysConfig config, Pageable pageable) {
{ return sysConfigRepository.findAll(getPredicate(config), pageable);
return configMapper.selectConfigList(config); }
private Predicate getPredicate(SysConfig config){
QSysConfig qSysConfig = QSysConfig.sysConfig;
List<Predicate> predicates = new ArrayList<>();
if(StringUtils.isNotEmpty(config.getConfigName())){
predicates.add(buildLike(qSysConfig.configName, config.getConfigName()));
}
if(StringUtils.isNotEmpty(config.getConfigType())){
predicates.add(buildEqual(qSysConfig.configType, config.getConfigType()));
}
if(StringUtils.isNotEmpty(config.getConfigKey())){
predicates.add(buildLike(qSysConfig.configKey, config.getConfigKey()));
}
if(config.getStartTime() != null){
predicates.add(buildGreaterThanOrEqualTo(qSysConfig.createTime, config.getStartTime()));
}
if(config.getEndTime() != null){
predicates.add(buildLessThanOrEqualTo(qSysConfig.createTime, config.getEndTime()));
}
return ExpressionUtils.allOf(predicates);
} }
/** /**
@ -96,14 +93,9 @@ public class SysConfigServiceImpl implements ISysConfigService
* @return 结果 * @return 结果
*/ */
@Override @Override
public int insertConfig(SysConfig config) public int insertConfig(SysConfig config) {
{ sysConfigRepository.save(config);
int row = configMapper.insertConfig(config); return 1;
if (row > 0)
{
CacheUtils.put(getCacheName(), getCacheKey(config.getConfigKey()), config.getConfigValue());
}
return row;
} }
/** /**
@ -113,14 +105,9 @@ public class SysConfigServiceImpl implements ISysConfigService
* @return 结果 * @return 结果
*/ */
@Override @Override
public int updateConfig(SysConfig config) public int updateConfig(SysConfig config) {
{ sysConfigRepository.save(config);
int row = configMapper.updateConfig(config); return 1;
if (row > 0)
{
CacheUtils.put(getCacheName(), getCacheKey(config.getConfigKey()), config.getConfigValue());
}
return row;
} }
/** /**
@ -129,34 +116,11 @@ public class SysConfigServiceImpl implements ISysConfigService
* @param ids 需要删除的数据ID * @param ids 需要删除的数据ID
* @return 结果 * @return 结果
*/ */
@Transactional
@Override @Override
public int deleteConfigByIds(String ids) public int deleteConfigByIds(String ids) {
{ sysConfigRepository.deleteByConfigIdIn(Arrays.asList(Convert.toLongArray(ids)));
Long[] configIds = Convert.toLongArray(ids); return 1;
for (Long configId : configIds)
{
SysConfig config = selectConfigById(configId);
if (StringUtils.equals(UserConstants.YES, config.getConfigType()))
{
throw new BusinessException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
}
}
int count = configMapper.deleteConfigByIds(Convert.toStrArray(ids));
if (count > 0)
{
CacheUtils.removeAll(getCacheName());
}
return count;
}
/**
* 清空缓存数据
*/
@Override
public void clearCache()
{
CacheUtils.removeAll(getCacheName());
} }
/** /**
@ -166,35 +130,18 @@ public class SysConfigServiceImpl implements ISysConfigService
* @return 结果 * @return 结果
*/ */
@Override @Override
public String checkConfigKeyUnique(SysConfig config) public String checkConfigKeyUnique(SysConfig config) {
{
Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId(); Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId();
SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey()); SysConfig info = sysConfigRepository.findFirstByConfigKey(config.getConfigKey());
if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) {
{
return UserConstants.CONFIG_KEY_NOT_UNIQUE; return UserConstants.CONFIG_KEY_NOT_UNIQUE;
} }
return UserConstants.CONFIG_KEY_UNIQUE; return UserConstants.CONFIG_KEY_UNIQUE;
} }
/** @CacheEvict(allEntries = true)
* 获取cache name @Override
* public void clearCache() {
* @return 缓存名
*/
private String getCacheName()
{
return Constants.SYS_CONFIG_CACHE;
}
/**
* 设置cache key
*
* @param configKey 参数键
* @return 缓存键key
*/
private String getCacheKey(String configKey)
{
return Constants.SYS_CONFIG_KEY + configKey;
} }
} }

View File

@ -1,21 +1,30 @@
package com.ruoyi.system.service.impl; package com.ruoyi.system.service.impl;
import java.util.ArrayList; import com.ruoyi.common.base.BaseService;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.mapper.SysDeptMapper; import com.ruoyi.system.repository.SysDeptRepository;
import com.ruoyi.system.repository.SysRoleRepository;
import com.ruoyi.system.repository.SysUserRepository;
import com.ruoyi.system.service.ISysDeptService; import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
/** /**
* 部门管理 服务实现 * 部门管理 服务实现
@ -23,10 +32,13 @@ import com.ruoyi.system.service.ISysDeptService;
* @author ruoyi * @author ruoyi
*/ */
@Service @Service
public class SysDeptServiceImpl implements ISysDeptService public class SysDeptServiceImpl extends BaseService implements ISysDeptService {
{
@Autowired @Autowired
private SysDeptMapper deptMapper; private SysDeptRepository sysDeptRepository;
@Autowired
private SysUserRepository sysUserRepository;
@Autowired
private SysRoleRepository sysRoleRepository;
/** /**
* 查询部门管理数据 * 查询部门管理数据
@ -35,10 +47,30 @@ public class SysDeptServiceImpl implements ISysDeptService
* @return 部门信息集合 * @return 部门信息集合
*/ */
@Override @Override
@DataScope(deptAlias = "d") public Page<SysDept> selectDeptList(SysDept dept, Pageable pageable) {
public List<SysDept> selectDeptList(SysDept dept) return sysDeptRepository.findAll(getSpecification(dept), pageable);
{ }
return deptMapper.selectDeptList(dept);
private Specification<SysDept> getSpecification(SysDept sysDept){
return new Specification<SysDept>() {
@Override
public Predicate toPredicate(Root<SysDept> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
if(StringUtils.isNotEmpty(sysDept.getDelFlag())){
predicates.add(criteriaBuilder.equal(root.get("delFlag").as(String.class), sysDept.getDelFlag()));
}
if(StringUtils.isNotEmpty(sysDept.getStatus())){
predicates.add(criteriaBuilder.equal(root.get("status").as(String.class), sysDept.getStatus()));
}
if(StringUtils.isNotEmpty(sysDept.getDeptName())){
predicates.add(criteriaBuilder.equal(root.get("deptName").as(String.class), "%" + sysDept.getDeptName() + "%"));
}
if(sysDept.getParent() != null && sysDept.getParent().getDeptId() != null){
predicates.add(criteriaBuilder.equal(root.get("parent").get("deptId").as(Long.class), sysDept.getParent().getDeptId()));
}
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
} }
/** /**
@ -48,36 +80,8 @@ public class SysDeptServiceImpl implements ISysDeptService
* @return 所有部门信息 * @return 所有部门信息
*/ */
@Override @Override
@DataScope(deptAlias = "d") public List<Ztree> selectDeptTree(SysDept dept) {
public List<Ztree> selectDeptTree(SysDept dept) List<SysDept> deptList = sysDeptRepository.findAll(getSpecification(dept));
{
List<SysDept> deptList = deptMapper.selectDeptList(dept);
List<Ztree> ztrees = initZtree(deptList);
return ztrees;
}
/**
* 查询部门管理树排除下级
*
* @param deptId 部门ID
* @return 所有部门信息
*/
@Override
@DataScope(deptAlias = "d")
public List<Ztree> selectDeptTreeExcludeChild(SysDept dept)
{
Long deptId = dept.getDeptId();
List<SysDept> deptList = deptMapper.selectDeptList(dept);
Iterator<SysDept> it = deptList.iterator();
while (it.hasNext())
{
SysDept d = (SysDept) it.next();
if (d.getDeptId().intValue() == deptId
|| ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
{
it.remove();
}
}
List<Ztree> ztrees = initZtree(deptList); List<Ztree> ztrees = initZtree(deptList);
return ztrees; return ztrees;
} }
@ -89,18 +93,14 @@ public class SysDeptServiceImpl implements ISysDeptService
* @return 部门列表数据权限 * @return 部门列表数据权限
*/ */
@Override @Override
public List<Ztree> roleDeptTreeData(SysRole role) public List<Ztree> roleDeptTreeData(SysRole role) {
{
Long roleId = role.getRoleId(); Long roleId = role.getRoleId();
List<Ztree> ztrees = new ArrayList<Ztree>(); List<Ztree> ztrees;
List<SysDept> deptList = selectDeptList(new SysDept()); List<SysDept> deptList = sysDeptRepository.findAll(getSpecification(new SysDept()));
if (StringUtils.isNotNull(roleId)) if (StringUtils.isNotNull(roleId)) {
{ SysRole sysRole = sysRoleRepository.findByRoleId(roleId);
List<String> roleDeptList = deptMapper.selectRoleDeptTree(roleId); ztrees = initZtree(deptList, sysRole.getDepts());
ztrees = initZtree(deptList, roleDeptList); } else {
}
else
{
ztrees = initZtree(deptList); ztrees = initZtree(deptList);
} }
return ztrees; return ztrees;
@ -112,35 +112,29 @@ public class SysDeptServiceImpl implements ISysDeptService
* @param deptList 部门列表 * @param deptList 部门列表
* @return 树结构列表 * @return 树结构列表
*/ */
public List<Ztree> initZtree(List<SysDept> deptList) public List<Ztree> initZtree(List<SysDept> deptList) {
{
return initZtree(deptList, null); return initZtree(deptList, null);
} }
/** /**
* 对象转部门树 * 对象转部门树
* *
* @param deptList 部门列表 * @param deptList 部门列表
* @param roleDeptList 角色已存在菜单列表 * @param roleDeptList 角色已存在菜单列表
* @return 树结构列表 * @return 树结构列表
*/ */
public List<Ztree> initZtree(List<SysDept> deptList, List<String> roleDeptList) public List<Ztree> initZtree(List<SysDept> deptList, List<SysDept> roleDeptList) {
{
List<Ztree> ztrees = new ArrayList<Ztree>(); List<Ztree> ztrees = new ArrayList<Ztree>();
boolean isCheck = StringUtils.isNotNull(roleDeptList); boolean isCheck = StringUtils.isNotNull(roleDeptList);
for (SysDept dept : deptList) for (SysDept dept : deptList) {
{ if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
{
Ztree ztree = new Ztree(); Ztree ztree = new Ztree();
ztree.setId(dept.getDeptId()); ztree.setId(dept.getDeptId());
ztree.setpId(dept.getParentId()); ztree.setpId(dept.getParentId());
ztree.setName(dept.getDeptName()); ztree.setName(dept.getDeptName());
ztree.setTitle(dept.getDeptName()); ztree.setTitle(dept.getDeptName());
if (isCheck) if (isCheck) {
{ ztree.setChecked(roleDeptList.contains(new SysDept(dept.getDeptId())));
ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
} }
ztrees.add(ztree); ztrees.add(ztree);
} }
@ -149,17 +143,14 @@ public class SysDeptServiceImpl implements ISysDeptService
} }
/** /**
* 查询部门 * 查询下级部门数
* *
* @param parentId 部门ID * @param deptId 部门ID
* @return 结果 * @return 结果
*/ */
@Override @Override
public int selectDeptCount(Long parentId) public int countChildren(Long deptId) {
{ return sysDeptRepository.countByDelFlagAndParent(BaseEntity.NOT_DELETED, new SysDept(deptId));
SysDept dept = new SysDept();
dept.setParentId(parentId);
return deptMapper.selectDeptCount(dept);
} }
/** /**
@ -169,10 +160,8 @@ public class SysDeptServiceImpl implements ISysDeptService
* @return 结果 true 存在 false 不存在 * @return 结果 true 存在 false 不存在
*/ */
@Override @Override
public boolean checkDeptExistUser(Long deptId) public boolean checkDeptExistUser(Long deptId) {
{ return sysUserRepository.countByDelFlagAndDept(BaseEntity.NOT_DELETED, new SysDept(deptId)) > 0;
int result = deptMapper.checkDeptExistUser(deptId);
return result > 0 ? true : false;
} }
/** /**
@ -181,10 +170,10 @@ public class SysDeptServiceImpl implements ISysDeptService
* @param deptId 部门ID * @param deptId 部门ID
* @return 结果 * @return 结果
*/ */
@Transactional
@Override @Override
public int deleteDeptById(Long deptId) public void deleteDeptById(Long deptId) {
{ sysDeptRepository.updateDelFlagByDeptId(BaseEntity.DELETED, deptId);
return deptMapper.deleteDeptById(deptId);
} }
/** /**
@ -193,17 +182,16 @@ public class SysDeptServiceImpl implements ISysDeptService
* @param dept 部门信息 * @param dept 部门信息
* @return 结果 * @return 结果
*/ */
@Transactional
@Override @Override
public int insertDept(SysDept dept) public SysDept insertDept(SysDept dept) {
{ SysDept info = sysDeptRepository.findById(dept.getParentId()).get();
SysDept info = deptMapper.selectDeptById(dept.getParentId());
// 如果父节点不为"正常"状态,则不允许新增子节点 // 如果父节点不为"正常"状态,则不允许新增子节点
if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
{
throw new BusinessException("部门停用,不允许新增"); throw new BusinessException("部门停用,不允许新增");
} }
dept.setAncestors(info.getAncestors() + "," + dept.getParentId()); setDeptCode(dept);
return deptMapper.insertDept(dept); return sysDeptRepository.save(dept);
} }
/** /**
@ -214,24 +202,14 @@ public class SysDeptServiceImpl implements ISysDeptService
*/ */
@Override @Override
@Transactional @Transactional
public int updateDept(SysDept dept) public SysDept updateDept(SysDept dept) {
{ setDeptCode(dept);
SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId()); sysDeptRepository.save(dept);
SysDept oldDept = selectDeptById(dept.getDeptId()); if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
{
String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
String oldAncestors = oldDept.getAncestors();
dept.setAncestors(newAncestors);
updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
}
int result = deptMapper.updateDept(dept);
if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
{
// 如果该部门是启用状态则启用该部门的所有上级部门 // 如果该部门是启用状态则启用该部门的所有上级部门
updateParentDeptStatus(dept); updateParentDeptStatus(dept);
} }
return result; return dept;
} }
/** /**
@ -239,33 +217,14 @@ public class SysDeptServiceImpl implements ISysDeptService
* *
* @param dept 当前部门 * @param dept 当前部门
*/ */
private void updateParentDeptStatus(SysDept dept) private void updateParentDeptStatus(SysDept dept) {
{ SysDept parent = null;
String updateBy = dept.getUpdateBy(); while ( (parent = dept.getParent()) != null ){
dept = deptMapper.selectDeptById(dept.getDeptId()); sysDeptRepository.updateStatusByDeptId(SysDept.STATUS_NORMAL, dept.getDeptId());
dept.setUpdateBy(updateBy); dept = parent;
deptMapper.updateDeptStatus(dept); }
} }
/**
* 修改子元素关系
*
* @param deptId 被修改的部门ID
* @param newAncestors 新的父ID集合
* @param oldAncestors 旧的父ID集合
*/
public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
{
List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
for (SysDept child : children)
{
child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
}
if (children.size() > 0)
{
deptMapper.updateDeptChildren(children);
}
}
/** /**
* 根据部门ID查询信息 * 根据部门ID查询信息
@ -274,21 +233,8 @@ public class SysDeptServiceImpl implements ISysDeptService
* @return 部门信息 * @return 部门信息
*/ */
@Override @Override
public SysDept selectDeptById(Long deptId) public SysDept selectDeptById(Long deptId) {
{ return sysDeptRepository.findById(deptId).orElseThrow(() -> new IllegalArgumentException("无效的数据"));
return deptMapper.selectDeptById(deptId);
}
/**
* 根据ID查询所有子部门正常状态
*
* @param deptId 部门ID
* @return 子部门数
*/
@Override
public int selectNormalChildrenDeptById(Long deptId)
{
return deptMapper.selectNormalChildrenDeptById(deptId);
} }
/** /**
@ -298,14 +244,26 @@ public class SysDeptServiceImpl implements ISysDeptService
* @return 结果 * @return 结果
*/ */
@Override @Override
public String checkDeptNameUnique(SysDept dept) public String checkDeptNameUnique(SysDept dept) {
{
Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId(); Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId()); SysDept info = sysDeptRepository.findFirstByDelFlagAndDeptNameAndParent(BaseEntity.NOT_DELETED, dept.getDeptName(), dept.getParent());
if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
{
return UserConstants.DEPT_NAME_NOT_UNIQUE; return UserConstants.DEPT_NAME_NOT_UNIQUE;
} }
return UserConstants.DEPT_NAME_UNIQUE; return UserConstants.DEPT_NAME_UNIQUE;
} }
public void setDeptCode(SysDept dept){
SysDept parent = dept.getParent();
String parentCode = parent.getCode();
SysDept max = sysDeptRepository.findFirstByParentOrderByCodeDesc(parent);
int next = 001;
if(max != null){
String maxCode = max.getCode();
String sequence = maxCode.substring(maxCode.length() - 3);
next = Integer.parseInt(sequence) + 1;
}
String code = String.format("%s%03d", parentCode, next);
dept.setCode(code);
}
} }

View File

@ -1,13 +1,24 @@
package com.ruoyi.system.service.impl; package com.ruoyi.system.service.impl;
import java.util.List; import com.querydsl.core.types.ExpressionUtils;
import org.springframework.beans.factory.annotation.Autowired; import com.querydsl.core.types.Predicate;
import org.springframework.stereotype.Service; import com.ruoyi.common.base.BaseService;
import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.QSysDictData;
import com.ruoyi.system.domain.SysDictData; import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.mapper.SysDictDataMapper; import com.ruoyi.system.repository.SysDictDataRepository;
import com.ruoyi.system.service.ISysDictDataService; import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.utils.DictUtils; import com.ruoyi.system.utils.DictUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** /**
* 字典 业务层处理 * 字典 业务层处理
@ -15,10 +26,9 @@ import com.ruoyi.system.utils.DictUtils;
* @author ruoyi * @author ruoyi
*/ */
@Service @Service
public class SysDictDataServiceImpl implements ISysDictDataService public class SysDictDataServiceImpl extends BaseService implements ISysDictDataService {
{
@Autowired @Autowired
private SysDictDataMapper dictDataMapper; private SysDictDataRepository sysDictDataRepository;
/** /**
* 根据条件分页查询字典数据 * 根据条件分页查询字典数据
@ -27,22 +37,47 @@ public class SysDictDataServiceImpl implements ISysDictDataService
* @return 字典数据集合信息 * @return 字典数据集合信息
*/ */
@Override @Override
public List<SysDictData> selectDictDataList(SysDictData dictData) public Page<SysDictData> selectDictDataList(SysDictData dictData, Pageable pageable) {
{ return sysDictDataRepository.findAll(getPredicate(dictData), pageable);
return dictDataMapper.selectDictDataList(dictData); }
private Predicate getPredicate(SysDictData dictData){
QSysDictData qSysDictData = QSysDictData.sysDictData;
List<Predicate> predicates = new ArrayList<>();
if(StringUtils.isNotEmpty(dictData.getDictType())){
predicates.add(buildEqual(qSysDictData.dictType, dictData.getDictType()));
}
if(StringUtils.isNotEmpty(dictData.getDictLabel())){
predicates.add(buildLike(qSysDictData.status, dictData.getDictLabel()));
}
if(StringUtils.isNotEmpty(dictData.getStatus())){
predicates.add(buildEqual(qSysDictData.status, dictData.getStatus()));
}
return ExpressionUtils.allOf(predicates);
}
/**
* 根据字典类型查询字典数据
*
* @param dictType 字典类型
* @return 字典数据集合信息
*/
@Override
public List<SysDictData> selectDictDataByType(String dictType) {
return sysDictDataRepository.findByDictType(dictType);
} }
/** /**
* 根据字典类型和字典键值查询字典数据信息 * 根据字典类型和字典键值查询字典数据信息
* *
* @param dictType 字典类型 * @param dictType 字典类型
* @param dictValue 字典键值 * @param dictValue 字典键值
* @return 字典标签 * @return 字典标签
*/ */
@Override @Override
public String selectDictLabel(String dictType, String dictValue) public String selectDictLabel(String dictType, String dictValue) {
{ SysDictData dictData = sysDictDataRepository.findFirstByDictTypeAndDictLabel(dictType, dictType);
return dictDataMapper.selectDictLabel(dictType, dictValue); return dictData == null ? dictData.getDictValue() : "";
} }
/** /**
@ -52,9 +87,21 @@ public class SysDictDataServiceImpl implements ISysDictDataService
* @return 字典数据 * @return 字典数据
*/ */
@Override @Override
public SysDictData selectDictDataById(Long dictCode) public SysDictData selectDictDataById(Long dictCode) {
{ return sysDictDataRepository.findById(dictCode).get();
return dictDataMapper.selectDictDataById(dictCode); }
/**
* 通过字典ID删除字典数据信息
*
* @param dictCode 字典数据ID
* @return 结果
*/
@Transactional
@Override
public int deleteDictDataById(Long dictCode) {
sysDictDataRepository.deleteById(dictCode);
return 1;
} }
/** /**
@ -63,15 +110,12 @@ public class SysDictDataServiceImpl implements ISysDictDataService
* @param ids 需要删除的数据 * @param ids 需要删除的数据
* @return 结果 * @return 结果
*/ */
@Transactional
@Override @Override
public int deleteDictDataByIds(String ids) public int deleteDictDataByIds(String ids) {
{ Collection<SysDictData> collection = toEntityIterable(toLongIterable(ids), id -> new SysDictData(id));
int row = dictDataMapper.deleteDictDataByIds(Convert.toStrArray(ids)); sysDictDataRepository.deleteAll(collection);
if (row > 0) return collection.size();
{
DictUtils.clearDictCache();
}
return row;
} }
/** /**
@ -81,14 +125,9 @@ public class SysDictDataServiceImpl implements ISysDictDataService
* @return 结果 * @return 结果
*/ */
@Override @Override
public int insertDictData(SysDictData dictData) public int insertDictData(SysDictData dictData) {
{ sysDictDataRepository.save(dictData);
int row = dictDataMapper.insertDictData(dictData); return 1;
if (row > 0)
{
DictUtils.clearDictCache();
}
return row;
} }
/** /**
@ -98,13 +137,8 @@ public class SysDictDataServiceImpl implements ISysDictDataService
* @return 结果 * @return 结果
*/ */
@Override @Override
public int updateDictData(SysDictData dictData) public int updateDictData(SysDictData dictData) {
{ sysDictDataRepository.save(dictData);
int row = dictDataMapper.updateDictData(dictData); return 1;
if (row > 0)
{
DictUtils.clearDictCache();
}
return row;
} }
} }

View File

@ -1,22 +1,27 @@
package com.ruoyi.system.service.impl; package com.ruoyi.system.service.impl;
import java.util.ArrayList; import com.querydsl.core.types.ExpressionUtils;
import java.util.List; import com.querydsl.core.types.Predicate;
import javax.annotation.PostConstruct; import com.ruoyi.common.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysDictData; import com.ruoyi.system.domain.QSysDictType;
import com.ruoyi.system.domain.SysDictType; import com.ruoyi.system.domain.SysDictType;
import com.ruoyi.system.mapper.SysDictDataMapper; import com.ruoyi.system.repository.SysDictDataRepository;
import com.ruoyi.system.mapper.SysDictTypeMapper; import com.ruoyi.system.repository.SysDictTypeRepository;
import com.ruoyi.system.service.ISysDictTypeService; import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.utils.DictUtils; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/** /**
* 字典 业务层处理 * 字典 业务层处理
@ -24,27 +29,11 @@ import com.ruoyi.system.utils.DictUtils;
* @author ruoyi * @author ruoyi
*/ */
@Service @Service
public class SysDictTypeServiceImpl implements ISysDictTypeService public class SysDictTypeServiceImpl extends BaseService implements ISysDictTypeService {
{
@Autowired @Autowired
private SysDictTypeMapper dictTypeMapper; private SysDictTypeRepository sysDictTypeRepository;
@Autowired @Autowired
private SysDictDataMapper dictDataMapper; private SysDictDataRepository sysDictDataRepository;
/**
* 项目启动时初始化字典到缓存
*/
@PostConstruct
public void init()
{
List<SysDictType> dictTypeList = dictTypeMapper.selectDictTypeAll();
for (SysDictType dictType : dictTypeList)
{
List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(dictType.getDictType());
DictUtils.setDictCache(dictType.getDictType(), dictDatas);
}
}
/** /**
* 根据条件分页查询字典类型 * 根据条件分页查询字典类型
@ -53,9 +42,29 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
* @return 字典类型集合信息 * @return 字典类型集合信息
*/ */
@Override @Override
public List<SysDictType> selectDictTypeList(SysDictType dictType) public Page<SysDictType> selectDictTypeList(SysDictType dictType, Pageable pageable) {
{ return sysDictTypeRepository.findAll(getPredicate(dictType), pageable);
return dictTypeMapper.selectDictTypeList(dictType); }
private Predicate getPredicate(SysDictType sysDictType){
QSysDictType qSysDictType = QSysDictType.sysDictType;
List<Predicate> predicates = new ArrayList<>();
if(StringUtils.isNotEmpty(sysDictType.getDictName())){
predicates.add(buildLike(qSysDictType.dictName, sysDictType.getDictName()));
}
if(StringUtils.isNotEmpty(sysDictType.getStatus())){
predicates.add(buildEqual(qSysDictType.status, sysDictType.getStatus()));
}
if(StringUtils.isNotEmpty(sysDictType.getDictType())){
predicates.add(buildLike(qSysDictType.dictType, sysDictType.getDictType()));
}
if(sysDictType.getStartTime() != null){
predicates.add(buildGreaterThanOrEqualTo(qSysDictType.createTime, sysDictType.getStartTime()));
}
if(sysDictType.getEndTime() != null){
predicates.add(buildLessThanOrEqualTo(qSysDictType.createTime, sysDictType.getEndTime()));
}
return ExpressionUtils.allOf(predicates);
} }
/** /**
@ -64,32 +73,8 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
* @return 字典类型集合信息 * @return 字典类型集合信息
*/ */
@Override @Override
public List<SysDictType> selectDictTypeAll() public List<SysDictType> selectDictTypeAll() {
{ return sysDictTypeRepository.findAll();
return dictTypeMapper.selectDictTypeAll();
}
/**
* 根据字典类型查询字典数据
*
* @param dictType 字典类型
* @return 字典数据集合信息
*/
@Override
public List<SysDictData> selectDictDataByType(String dictType)
{
List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
if (StringUtils.isNotEmpty(dictDatas))
{
return dictDatas;
}
dictDatas = dictDataMapper.selectDictDataByType(dictType);
if (StringUtils.isNotEmpty(dictDatas))
{
DictUtils.setDictCache(dictType, dictDatas);
return dictDatas;
}
return null;
} }
/** /**
@ -99,9 +84,8 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
* @return 字典类型 * @return 字典类型
*/ */
@Override @Override
public SysDictType selectDictTypeById(Long dictId) public SysDictType selectDictTypeById(Long dictId) {
{ return sysDictTypeRepository.findById(dictId).get();
return dictTypeMapper.selectDictTypeById(dictId);
} }
/** /**
@ -110,10 +94,21 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
* @param dictType 字典类型 * @param dictType 字典类型
* @return 字典类型 * @return 字典类型
*/ */
public SysDictType selectDictTypeByType(String dictType) {
return sysDictTypeRepository.findFirstByDictType(dictType);
}
/**
* 通过字典ID删除字典信息
*
* @param dictId 字典ID
* @return 结果
*/
@Transactional
@Override @Override
public SysDictType selectDictTypeByType(String dictType) public int deleteDictTypeById(Long dictId) {
{ sysDictTypeRepository.deleteById(dictId);
return dictTypeMapper.selectDictTypeByType(dictType); return 1;
} }
/** /**
@ -122,33 +117,18 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
* @param ids 需要删除的数据 * @param ids 需要删除的数据
* @return 结果 * @return 结果
*/ */
@Transactional
@Override @Override
public int deleteDictTypeByIds(String ids) public int deleteDictTypeByIds(String ids) throws BusinessException {
{
Long[] dictIds = Convert.toLongArray(ids); Long[] dictIds = Convert.toLongArray(ids);
for (Long dictId : dictIds) for (Long dictId : dictIds) {
{
SysDictType dictType = selectDictTypeById(dictId); SysDictType dictType = selectDictTypeById(dictId);
if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) if (sysDictDataRepository.countByDictType(dictType.getDictType()) > 0) {
{
throw new BusinessException(String.format("%1$s已分配,不能删除", dictType.getDictName())); throw new BusinessException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
} }
deleteDictTypeById(dictId);
} }
int count = dictTypeMapper.deleteDictTypeByIds(dictIds); return dictIds.length;
if (count > 0)
{
DictUtils.clearDictCache();
}
return count;
}
/**
* 清空缓存数据
*/
@Override
public void clearCache()
{
DictUtils.clearDictCache();
} }
/** /**
@ -158,14 +138,9 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
* @return 结果 * @return 结果
*/ */
@Override @Override
public int insertDictType(SysDictType dictType) public int insertDictType(SysDictType dictType) {
{ sysDictTypeRepository.save(dictType);
int row = dictTypeMapper.insertDictType(dictType); return 1;
if (row > 0)
{
DictUtils.clearDictCache();
}
return row;
} }
/** /**
@ -176,16 +151,11 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
*/ */
@Override @Override
@Transactional @Transactional
public int updateDictType(SysDictType dictType) public int updateDictType(SysDictType dictType) {
{ SysDictType oldDict = sysDictTypeRepository.findById(dictType.getDictId()).get();
SysDictType oldDict = dictTypeMapper.selectDictTypeById(dictType.getDictId()); sysDictDataRepository.updateDictType(dictType.getDictType(), oldDict.getDictType());
dictDataMapper.updateDictDataType(oldDict.getDictType(), dictType.getDictType()); sysDictTypeRepository.save(dictType);
int row = dictTypeMapper.updateDictType(dictType); return 1;
if (row > 0)
{
DictUtils.clearDictCache();
}
return row;
} }
/** /**
@ -195,12 +165,10 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
* @return 结果 * @return 结果
*/ */
@Override @Override
public String checkDictTypeUnique(SysDictType dict) public String checkDictTypeUnique(SysDictType dict) {
{
Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId(); Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
SysDictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType()); SysDictType dictType = sysDictTypeRepository.findFirstByDictType(dict.getDictType());
if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
{
return UserConstants.DICT_TYPE_NOT_UNIQUE; return UserConstants.DICT_TYPE_NOT_UNIQUE;
} }
return UserConstants.DICT_TYPE_UNIQUE; return UserConstants.DICT_TYPE_UNIQUE;
@ -212,15 +180,11 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
* @param dictType 字典类型 * @param dictType 字典类型
* @return 所有字典类型 * @return 所有字典类型
*/ */
@Override public List<Ztree> selectDictTree(SysDictType dictType) {
public List<Ztree> selectDictTree(SysDictType dictType)
{
List<Ztree> ztrees = new ArrayList<Ztree>(); List<Ztree> ztrees = new ArrayList<Ztree>();
List<SysDictType> dictList = dictTypeMapper.selectDictTypeList(dictType); List<SysDictType> dictList = sysDictTypeRepository.findAll();
for (SysDictType dict : dictList) for (SysDictType dict : dictList) {
{ if (UserConstants.DICT_NORMAL.equals(dict.getStatus())) {
if (UserConstants.DICT_NORMAL.equals(dict.getStatus()))
{
Ztree ztree = new Ztree(); Ztree ztree = new Ztree();
ztree.setId(dict.getDictId()); ztree.setId(dict.getDictId());
ztree.setName(transDictName(dict)); ztree.setName(transDictName(dict));
@ -231,8 +195,13 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService
return ztrees; return ztrees;
} }
public String transDictName(SysDictType dictType) @CacheEvict(allEntries = true)
{ @Override
public void clearCache() {
}
public String transDictName(SysDictType dictType) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
sb.append("(" + dictType.getDictName() + ")"); sb.append("(" + dictType.getDictName() + ")");
sb.append("&nbsp;&nbsp;&nbsp;" + dictType.getDictType()); sb.append("&nbsp;&nbsp;&nbsp;" + dictType.getDictType());

View File

@ -33,8 +33,6 @@ public class SysLogininforServiceImpl extends BaseService implements ISysLoginin
private SysLogininfoRepository sysLogininfoRepository; private SysLogininfoRepository sysLogininfoRepository;
@Autowired @Autowired
private JdbcTemplate jdbcTemplate; private JdbcTemplate jdbcTemplate;
@Autowired
private EntityManager entityManager;
/** /**
* 新增系统登录日志 * 新增系统登录日志

View File

@ -1,25 +1,26 @@
package com.ruoyi.system.service.impl; package com.ruoyi.system.service.impl;
import java.text.MessageFormat; import com.google.common.collect.Lists;
import java.util.ArrayList; import com.ruoyi.common.base.BaseService;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysMenu; import com.ruoyi.system.domain.SysMenu;
import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.SysMenuMapper; import com.ruoyi.system.repository.SysMenuRepository;
import com.ruoyi.system.mapper.SysRoleMenuMapper; import com.ruoyi.system.repository.SysRoleRepository;
import com.ruoyi.system.repository.SysUserRepository;
import com.ruoyi.system.service.ISysMenuService; import com.ruoyi.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.*;
import java.text.MessageFormat;
import java.util.*;
/** /**
* 菜单 业务层处理 * 菜单 业务层处理
@ -27,15 +28,15 @@ import com.ruoyi.system.service.ISysMenuService;
* @author ruoyi * @author ruoyi
*/ */
@Service @Service
public class SysMenuServiceImpl implements ISysMenuService public class SysMenuServiceImpl extends BaseService implements ISysMenuService {
{
public static final String PREMISSION_STRING = "perms[\"{0}\"]"; public static final String PREMISSION_STRING = "perms[\"{0}\"]";
@Autowired @Autowired
private SysMenuMapper menuMapper; private SysMenuRepository sysMenuRepository;
@Autowired @Autowired
private SysRoleMenuMapper roleMenuMapper; private SysUserRepository sysUserRepository;
@Autowired
private SysRoleRepository sysRoleRepository;
/** /**
* 根据用户查询菜单 * 根据用户查询菜单
@ -44,19 +45,38 @@ public class SysMenuServiceImpl implements ISysMenuService
* @return 菜单列表 * @return 菜单列表
*/ */
@Override @Override
public List<SysMenu> selectMenusByUser(SysUser user) public List<SysMenu> selectMenusByUser(SysUser user) {
{
List<SysMenu> menus = new LinkedList<SysMenu>(); List<SysMenu> menus = new LinkedList<SysMenu>();
// 管理员显示所有菜单信息 // 管理员显示所有菜单信息
if (user.isAdmin()) if (user.isAdmin()) {
{ menus = sysMenuRepository.findAllByMenuTypeInAndVisibleOrderByOrderNum(
menus = menuMapper.selectMenuNormalAll(); Lists.newArrayList(SysMenu.MENU_TYPE_PRIMARY, SysMenu.MENU_TYPE_SECONDARY), SysMenu.MENU_VISIABLE);
} else {
user = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, user.getUserId());
Set<SysRole> roles = user.getRoles();
menus = sysMenuRepository.findAll(new Specification<SysMenu>() {
@Override
public Predicate toPredicate(Root<SysMenu> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
if(!roles.isEmpty()){
for(SysRole role : roles){
predicates.add(criteriaBuilder.isMember(role, root.get("roles")));
}
}
Expression<String> type = root.get("menuType").as(String.class);
CriteriaBuilder.In<String> in = criteriaBuilder.in(type);
in.value(SysMenu.MENU_TYPE_PRIMARY);
in.value(SysMenu.MENU_TYPE_SECONDARY);
predicates.add(in);
predicates.add(criteriaBuilder.equal(root.get("visible").as(String.class), SysMenu.MENU_VISIABLE));
query.orderBy(criteriaBuilder.asc(root.get("orderNum").as(String.class)));
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
});
} }
else return getChildPerms(menus, SysMenu.ROOT_ID);
{
menus = menuMapper.selectMenusByUserId(user.getUserId());
}
return getChildPerms(menus, 0);
} }
/** /**
@ -65,37 +85,71 @@ public class SysMenuServiceImpl implements ISysMenuService
* @return 所有菜单信息 * @return 所有菜单信息
*/ */
@Override @Override
public List<SysMenu> selectMenuList(SysMenu menu, Long userId) public List<SysMenu> selectMenuList(SysMenu menu, Long userId) {
{
List<SysMenu> menuList = null; List<SysMenu> menuList = null;
if (SysUser.isAdmin(userId)) if (SysUser.isAdmin(userId)) {
{ menuList = sysMenuRepository.findAll(getSpecificationForAdmin(menu));
menuList = menuMapper.selectMenuList(menu); } else {
} SysUser user = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId);
else Set<SysRole> roles = user.getRoles();
{ menuList = sysMenuRepository.findAll(getSpecification(menu, roles));
menu.getParams().put("userId", userId);
menuList = menuMapper.selectMenuListByUserId(menu);
} }
return menuList; return menuList;
} }
private Specification<SysMenu> getSpecificationForAdmin(SysMenu sysMenu){
return new Specification<SysMenu>() {
@Override
public Predicate toPredicate(Root<SysMenu> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
if(StringUtils.isNotEmpty(sysMenu.getMenuName())){
predicates.add(criteriaBuilder.like(root.get("menuName").as(String.class), "%" + sysMenu.getMenuName() + "%"));
}
if(StringUtils.isNotEmpty(sysMenu.getVisible())){
predicates.add(criteriaBuilder.equal(root.get("visible").as(String.class), sysMenu.getVisible()));
}
query.orderBy(criteriaBuilder.asc(root.get("orderNum").as(String.class)));
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
}
private Specification<SysMenu> getSpecification(SysMenu sysMenu, Set<SysRole> roles){
return new Specification<SysMenu>() {
@Override
public Predicate toPredicate(Root<SysMenu> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
if(!roles.isEmpty()){
for(SysRole role : roles){
predicates.add(criteriaBuilder.isMember(role, root.get("roles")));
}
}
if(StringUtils.isNotEmpty(sysMenu.getMenuName())){
predicates.add(criteriaBuilder.like(root.get("menuName").as(String.class), "%" + sysMenu.getMenuName() + "%"));
}
if(StringUtils.isNotEmpty(sysMenu.getVisible())){
predicates.add(criteriaBuilder.equal(root.get("visible").as(String.class), sysMenu.getVisible()));
}
query.orderBy(criteriaBuilder.asc(root.get("orderNum").as(String.class)));
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
}
/** /**
* 查询菜单集合 * 查询菜单集合
* *
* @return 所有菜单信息 * @return 所有菜单信息
*/ */
@Override @Override
public List<SysMenu> selectMenuAll(Long userId) public List<SysMenu> selectMenuAll(Long userId) {
{
List<SysMenu> menuList = null; List<SysMenu> menuList = null;
if (SysUser.isAdmin(userId)) if (SysUser.isAdmin(userId)) {
{ menuList = sysMenuRepository.findAll();
menuList = menuMapper.selectMenuAll(); } else {
} SysUser user = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId);
else Set<SysRole> roles = user.getRoles();
{ menuList = sysMenuRepository.findAll(getSpecification(new SysMenu(), roles));
menuList = menuMapper.selectMenuAllByUserId(userId);
} }
return menuList; return menuList;
} }
@ -107,14 +161,14 @@ public class SysMenuServiceImpl implements ISysMenuService
* @return 权限列表 * @return 权限列表
*/ */
@Override @Override
public Set<String> selectPermsByUserId(Long userId) public Set<String> selectPermsByUserId(Long userId) {
{ SysUser sysUser = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId);
List<String> perms = menuMapper.selectPermsByUserId(userId); Set<SysRole> roles = sysUser.getRoles();
List<SysMenu> menus = sysMenuRepository.findAll(getSpecification(new SysMenu(), roles));
Set<String> permsSet = new HashSet<>(); Set<String> permsSet = new HashSet<>();
for (String perm : perms) for(SysMenu sysMenu : menus){
{ String perm = sysMenu.getPerms();
if (StringUtils.isNotEmpty(perm)) if (StringUtils.isNotEmpty(perm)) {
{
permsSet.addAll(Arrays.asList(perm.trim().split(","))); permsSet.addAll(Arrays.asList(perm.trim().split(",")));
} }
} }
@ -128,18 +182,14 @@ public class SysMenuServiceImpl implements ISysMenuService
* @return 菜单列表 * @return 菜单列表
*/ */
@Override @Override
public List<Ztree> roleMenuTreeData(SysRole role, Long userId) public List<Ztree> roleMenuTreeData(SysRole role, Long userId) {
{
Long roleId = role.getRoleId(); Long roleId = role.getRoleId();
List<Ztree> ztrees = new ArrayList<Ztree>(); List<Ztree> ztrees = new ArrayList<Ztree>();
List<SysMenu> menuList = selectMenuAll(userId); List<SysMenu> menuList = selectMenuAll(userId);
if (StringUtils.isNotNull(roleId)) if (StringUtils.isNotNull(roleId)) {
{ List<SysMenu> menus = sysMenuRepository.findAllByRolesContaining(new SysRole(roleId));
List<String> roleMenuList = menuMapper.selectMenuTree(roleId); ztrees = initZtree(menuList, menus, true);
ztrees = initZtree(menuList, roleMenuList, true); } else {
}
else
{
ztrees = initZtree(menuList, null, true); ztrees = initZtree(menuList, null, true);
} }
return ztrees; return ztrees;
@ -151,8 +201,7 @@ public class SysMenuServiceImpl implements ISysMenuService
* @return 菜单列表 * @return 菜单列表
*/ */
@Override @Override
public List<Ztree> menuTreeData(Long userId) public List<Ztree> menuTreeData(Long userId) {
{
List<SysMenu> menuList = selectMenuAll(userId); List<SysMenu> menuList = selectMenuAll(userId);
List<Ztree> ztrees = initZtree(menuList); List<Ztree> ztrees = initZtree(menuList);
return ztrees; return ztrees;
@ -164,14 +213,11 @@ public class SysMenuServiceImpl implements ISysMenuService
* @return 权限列表 * @return 权限列表
*/ */
@Override @Override
public LinkedHashMap<String, String> selectPermsAll(Long userId) public LinkedHashMap<String, String> selectPermsAll(Long userId) {
{
LinkedHashMap<String, String> section = new LinkedHashMap<>(); LinkedHashMap<String, String> section = new LinkedHashMap<>();
List<SysMenu> permissions = selectMenuAll(userId); List<SysMenu> permissions = selectMenuAll(userId);
if (StringUtils.isNotEmpty(permissions)) if (StringUtils.isNotEmpty(permissions)) {
{ for (SysMenu menu : permissions) {
for (SysMenu menu : permissions)
{
section.put(menu.getUrl(), MessageFormat.format(PREMISSION_STRING, menu.getPerms())); section.put(menu.getUrl(), MessageFormat.format(PREMISSION_STRING, menu.getPerms()));
} }
} }
@ -184,45 +230,39 @@ public class SysMenuServiceImpl implements ISysMenuService
* @param menuList 菜单列表 * @param menuList 菜单列表
* @return 树结构列表 * @return 树结构列表
*/ */
public List<Ztree> initZtree(List<SysMenu> menuList) public List<Ztree> initZtree(List<SysMenu> menuList) {
{
return initZtree(menuList, null, false); return initZtree(menuList, null, false);
} }
/** /**
* 对象转菜单树 * 对象转菜单树
* *
* @param menuList 菜单列表 * @param menuList 菜单列表
* @param roleMenuList 角色已存在菜单列表 * @param roleMenuList 角色已存在菜单列表
* @param permsFlag 是否需要显示权限标识 * @param permsFlag 是否需要显示权限标识
* @return 树结构列表 * @return 树结构列表
*/ */
public List<Ztree> initZtree(List<SysMenu> menuList, List<String> roleMenuList, boolean permsFlag) public List<Ztree> initZtree(List<SysMenu> menuList, List<SysMenu> roleMenuList, boolean permsFlag) {
{
List<Ztree> ztrees = new ArrayList<Ztree>(); List<Ztree> ztrees = new ArrayList<Ztree>();
boolean isCheck = StringUtils.isNotNull(roleMenuList); boolean isCheck = StringUtils.isNotNull(roleMenuList);
for (SysMenu menu : menuList) for (SysMenu menu : menuList) {
{
Ztree ztree = new Ztree(); Ztree ztree = new Ztree();
ztree.setId(menu.getMenuId()); ztree.setId(menu.getMenuId());
ztree.setpId(menu.getParentId()); ztree.setpId(menu.getParentId());
ztree.setName(transMenuName(menu, permsFlag)); ztree.setName(transMenuName(menu, permsFlag));
ztree.setTitle(menu.getMenuName()); ztree.setTitle(menu.getMenuName());
if (isCheck) if (isCheck) {
{ ztree.setChecked(roleMenuList.contains(menu));
ztree.setChecked(roleMenuList.contains(menu.getMenuId() + menu.getPerms()));
} }
ztrees.add(ztree); ztrees.add(ztree);
} }
return ztrees; return ztrees;
} }
public String transMenuName(SysMenu menu, boolean permsFlag) public String transMenuName(SysMenu menu, boolean permsFlag) {
{
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
sb.append(menu.getMenuName()); sb.append(menu.getMenuName());
if (permsFlag) if (permsFlag) {
{
sb.append("<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + menu.getPerms() + "</font>"); sb.append("<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + menu.getPerms() + "</font>");
} }
return sb.toString(); return sb.toString();
@ -235,9 +275,9 @@ public class SysMenuServiceImpl implements ISysMenuService
* @return 结果 * @return 结果
*/ */
@Override @Override
public int deleteMenuById(Long menuId) public int deleteMenuById(Long menuId) {
{ sysMenuRepository.deleteById(menuId);
return menuMapper.deleteMenuById(menuId); return 1;
} }
/** /**
@ -247,9 +287,8 @@ public class SysMenuServiceImpl implements ISysMenuService
* @return 菜单信息 * @return 菜单信息
*/ */
@Override @Override
public SysMenu selectMenuById(Long menuId) public SysMenu selectMenuById(Long menuId) {
{ return sysMenuRepository.findById(menuId).get();
return menuMapper.selectMenuById(menuId);
} }
/** /**
@ -259,9 +298,8 @@ public class SysMenuServiceImpl implements ISysMenuService
* @return 结果 * @return 结果
*/ */
@Override @Override
public int selectCountMenuByParentId(Long parentId) public int selectCountMenuByParentId(Long parentId) {
{ return sysMenuRepository.countByParent(new SysMenu(parentId));
return menuMapper.selectCountMenuByParentId(parentId);
} }
/** /**
@ -271,9 +309,8 @@ public class SysMenuServiceImpl implements ISysMenuService
* @return 结果 * @return 结果
*/ */
@Override @Override
public int selectCountRoleMenuByMenuId(Long menuId) public int selectCountRoleMenuByMenuId(Long menuId) {
{ return sysRoleRepository.countByMenusContaining(new SysMenu(menuId));
return roleMenuMapper.selectCountRoleMenuByMenuId(menuId);
} }
/** /**
@ -282,10 +319,10 @@ public class SysMenuServiceImpl implements ISysMenuService
* @param menu 菜单信息 * @param menu 菜单信息
* @return 结果 * @return 结果
*/ */
@Transactional
@Override @Override
public int insertMenu(SysMenu menu) public SysMenu insertMenu(SysMenu menu) {
{ return sysMenuRepository.save(menu);
return menuMapper.insertMenu(menu);
} }
/** /**
@ -294,10 +331,10 @@ public class SysMenuServiceImpl implements ISysMenuService
* @param menu 菜单信息 * @param menu 菜单信息
* @return 结果 * @return 结果
*/ */
@Transactional
@Override @Override
public int updateMenu(SysMenu menu) public SysMenu updateMenu(SysMenu menu) {
{ return sysMenuRepository.save(menu);
return menuMapper.updateMenu(menu);
} }
/** /**
@ -307,12 +344,10 @@ public class SysMenuServiceImpl implements ISysMenuService
* @return 结果 * @return 结果
*/ */
@Override @Override
public String checkMenuNameUnique(SysMenu menu) public String checkMenuNameUnique(SysMenu menu) {
{
Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId(); Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
SysMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId()); SysMenu info = sysMenuRepository.findFirstByMenuNameAndParent(menu.getMenuName(), new SysMenu(menu.getParentId()));
if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) {
{
return UserConstants.MENU_NAME_NOT_UNIQUE; return UserConstants.MENU_NAME_NOT_UNIQUE;
} }
return UserConstants.MENU_NAME_UNIQUE; return UserConstants.MENU_NAME_UNIQUE;
@ -321,19 +356,16 @@ public class SysMenuServiceImpl implements ISysMenuService
/** /**
* 根据父节点的ID获取所有子节点 * 根据父节点的ID获取所有子节点
* *
* @param list 分类表 * @param list 分类表
* @param parentId 传入的父节点ID * @param parentId 传入的父节点ID
* @return String * @return String
*/ */
public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) public List<SysMenu> getChildPerms(List<SysMenu> list, Long parentId) {
{
List<SysMenu> returnList = new ArrayList<SysMenu>(); List<SysMenu> returnList = new ArrayList<SysMenu>();
for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext();) for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext(); ) {
{
SysMenu t = (SysMenu) iterator.next(); SysMenu t = (SysMenu) iterator.next();
// 根据传入的某个父节点ID,遍历该父节点的所有子节点 // 根据传入的某个父节点ID,遍历该父节点的所有子节点
if (t.getParentId() == parentId) if((parentId == null && t.getParentId() == null) || (parentId != null && t.getParentId() != null && parentId.equals(t.getParentId()))){
{
recursionFn(list, t); recursionFn(list, t);
returnList.add(t); returnList.add(t);
} }
@ -347,16 +379,18 @@ public class SysMenuServiceImpl implements ISysMenuService
* @param list * @param list
* @param t * @param t
*/ */
private void recursionFn(List<SysMenu> list, SysMenu t) private void recursionFn(List<SysMenu> list, SysMenu t) {
{
// 得到子节点列表 // 得到子节点列表
List<SysMenu> childList = getChildList(list, t); List<SysMenu> childList = getChildList(list, t);
t.setChildren(childList); t.setChildren(childList);
for (SysMenu tChild : childList) for (SysMenu tChild : childList) {
{ if (hasChild(list, tChild)) {
if (hasChild(list, tChild)) // 判断是否有子节点
{ Iterator<SysMenu> it = childList.iterator();
recursionFn(list, tChild); while (it.hasNext()) {
SysMenu n = (SysMenu) it.next();
recursionFn(list, n);
}
} }
} }
} }
@ -364,15 +398,12 @@ public class SysMenuServiceImpl implements ISysMenuService
/** /**
* 得到子节点列表 * 得到子节点列表
*/ */
private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
{
List<SysMenu> tlist = new ArrayList<SysMenu>(); List<SysMenu> tlist = new ArrayList<SysMenu>();
Iterator<SysMenu> it = list.iterator(); Iterator<SysMenu> it = list.iterator();
while (it.hasNext()) while (it.hasNext()) {
{
SysMenu n = (SysMenu) it.next(); SysMenu n = (SysMenu) it.next();
if (n.getParentId().longValue() == t.getMenuId().longValue()) if (t.getMenuId().equals(n.getParentId())) {
{
tlist.add(n); tlist.add(n);
} }
} }
@ -382,8 +413,7 @@ public class SysMenuServiceImpl implements ISysMenuService
/** /**
* 判断是否有子节点 * 判断是否有子节点
*/ */
private boolean hasChild(List<SysMenu> list, SysMenu t) private boolean hasChild(List<SysMenu> list, SysMenu t) {
{
return getChildList(list, t).size() > 0 ? true : false; return getChildList(list, t).size() > 0 ? true : false;
} }
} }

View File

@ -1,60 +1,79 @@
package com.ruoyi.system.service.impl; package com.ruoyi.system.service.impl;
import java.util.ArrayList; import com.querydsl.core.types.ExpressionUtils;
import java.util.Arrays; import com.querydsl.core.types.Predicate;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.annotation.DataScope; import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils; import com.ruoyi.system.domain.QSysRole;
import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.domain.SysRoleDept; import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.SysRoleMenu;
import com.ruoyi.system.domain.SysUserRole; import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysRoleDeptMapper; import com.ruoyi.system.repository.SysRoleRepository;
import com.ruoyi.system.mapper.SysRoleMapper; import com.ruoyi.system.repository.SysUserRepository;
import com.ruoyi.system.mapper.SysRoleMenuMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysRoleService; import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.base.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
/** /**
* 角色 业务层处理 * 角色 业务层处理
* *
* @author ruoyi * @author ruoyi
*/ */
@DataScope(userFieldName = "user")
@Service @Service
public class SysRoleServiceImpl implements ISysRoleService public class SysRoleServiceImpl extends BusinessService implements ISysRoleService {
{
@Autowired
private SysRoleMapper roleMapper;
@Autowired @Autowired
private SysRoleMenuMapper roleMenuMapper; private SysRoleRepository sysRoleRepository;
@Autowired @Autowired
private SysUserRoleMapper userRoleMapper; private SysUserRepository sysUserRepository;
@Autowired
private SysRoleDeptMapper roleDeptMapper;
/** /**
* 根据条件分页查询角色数据 * 根据条件分页查询角色数据
* *
* @param role 角色信息 * @param role 角色信息
* @param user
* @return 角色数据集合信息 * @return 角色数据集合信息
*/ */
@Override @Override
@DataScope(deptAlias = "d") public Page<SysRole> selectRoleList(SysRole role, Pageable pageable, SysUser user) {
public List<SysRole> selectRoleList(SysRole role) return sysRoleRepository.findAll(getPredicate(role, user), pageable);
{ }
return roleMapper.selectRoleList(role);
public Predicate getPredicate(SysRole role, SysUser user){
QSysRole qSysRole = QSysRole.sysRole;
List<Predicate> predicates = new ArrayList<>();
predicates.add(buildEqual(qSysRole.delFlag, BaseEntity.NOT_DELETED));
if(StringUtils.isNotEmpty(role.getRoleName())){
predicates.add(buildLike(qSysRole.roleName, role.getRoleName()));
}
if(StringUtils.isNotEmpty(role.getStatus())){
predicates.add(buildEqual(qSysRole.status, role.getStatus()));
}
if(StringUtils.isNotEmpty(role.getRoleKey())){
predicates.add(buildLike(qSysRole.roleKey, role.getRoleKey()));
}
if(role.getDataScope() != null){
predicates.add(buildEqual(qSysRole.dataScope, role.getDataScope()));
}
if(role.getStartTime() != null){
predicates.add(buildGreaterThanOrEqualTo(qSysRole.createTime, role.getStartTime()));
}
if(role.getEndTime() != null){
predicates.add(buildLessThanOrEqualTo(qSysRole.createTime, role.getEndTime()));
}
// predicates.add(buildDataPermission(qSysRole.depts, user.getUserId()));
return ExpressionUtils.allOf(predicates);
} }
/** /**
@ -64,16 +83,12 @@ public class SysRoleServiceImpl implements ISysRoleService
* @return 权限列表 * @return 权限列表
*/ */
@Override @Override
public Set<String> selectRoleKeys(Long userId) public Set<String> selectRoleKeys(Long userId) {
{ SysUser sysUser = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId);
List<SysRole> perms = roleMapper.selectRolesByUserId(userId); Set<SysRole> roles = sysUser.getRoles();
Set<String> permsSet = new HashSet<>(); Set<String> permsSet = new HashSet<>();
for (SysRole perm : perms) for (SysRole perm : roles) {
{ permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
if (StringUtils.isNotNull(perm))
{
permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
}
} }
return permsSet; return permsSet;
} }
@ -85,22 +100,9 @@ public class SysRoleServiceImpl implements ISysRoleService
* @return 角色列表 * @return 角色列表
*/ */
@Override @Override
public List<SysRole> selectRolesByUserId(Long userId) public Set<SysRole> selectRolesByUserId(Long userId) {
{ SysUser sysUser = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId);
List<SysRole> userRoles = roleMapper.selectRolesByUserId(userId); return sysUser.getRoles();
List<SysRole> roles = selectRoleAll();
for (SysRole role : roles)
{
for (SysRole userRole : userRoles)
{
if (role.getRoleId().longValue() == userRole.getRoleId().longValue())
{
role.setFlag(true);
break;
}
}
}
return roles;
} }
/** /**
@ -109,9 +111,8 @@ public class SysRoleServiceImpl implements ISysRoleService
* @return 角色列表 * @return 角色列表
*/ */
@Override @Override
public List<SysRole> selectRoleAll() public List<SysRole> selectRoleAll() {
{ return sysRoleRepository.findAll(getPredicate(new SysRole(), new SysUser()), Pageable.unpaged()).getContent();
return SpringUtils.getAopProxy(this).selectRoleList(new SysRole());
} }
/** /**
@ -121,9 +122,8 @@ public class SysRoleServiceImpl implements ISysRoleService
* @return 角色对象信息 * @return 角色对象信息
*/ */
@Override @Override
public SysRole selectRoleById(Long roleId) public SysRole selectRoleById(Long roleId) {
{ return sysRoleRepository.findById(roleId).get();
return roleMapper.selectRoleById(roleId);
} }
/** /**
@ -132,10 +132,11 @@ public class SysRoleServiceImpl implements ISysRoleService
* @param roleId 角色ID * @param roleId 角色ID
* @return 结果 * @return 结果
*/ */
@Transactional
@Override @Override
public boolean deleteRoleById(Long roleId) public boolean deleteRoleById(Long roleId) {
{ sysRoleRepository.deleteById(roleId);
return roleMapper.deleteRoleById(roleId) > 0 ? true : false; return true;
} }
/** /**
@ -144,20 +145,19 @@ public class SysRoleServiceImpl implements ISysRoleService
* @param ids 需要删除的数据ID * @param ids 需要删除的数据ID
* @throws Exception * @throws Exception
*/ */
@Transactional
@Override @Override
public int deleteRoleByIds(String ids) throws BusinessException public int deleteRoleByIds(String ids) throws BusinessException {
{
Long[] roleIds = Convert.toLongArray(ids); Long[] roleIds = Convert.toLongArray(ids);
for (Long roleId : roleIds) for (Long roleId : roleIds) {
{
checkRoleAllowed(new SysRole(roleId)); checkRoleAllowed(new SysRole(roleId));
SysRole role = selectRoleById(roleId); SysRole role = selectRoleById(roleId);
if (countUserRoleByRoleId(roleId) > 0) if (countUserRoleByRoleId(roleId) > 0) {
{
throw new BusinessException(String.format("%1$s已分配,不能删除", role.getRoleName())); throw new BusinessException(String.format("%1$s已分配,不能删除", role.getRoleName()));
} }
deleteRoleById(roleId);
} }
return roleMapper.deleteRoleByIds(roleIds); return roleIds.length;
} }
/** /**
@ -168,94 +168,33 @@ public class SysRoleServiceImpl implements ISysRoleService
*/ */
@Override @Override
@Transactional @Transactional
public int insertRole(SysRole role) public SysRole insertRole(SysRole role) {
{ return sysRoleRepository.save(role);
// 新增角色信息
roleMapper.insertRole(role);
return insertRoleMenu(role);
} }
/** /**
* 修改保存角色信息 * 修改保存角色信息
*
* @param role 角色信息 * @param role 角色信息
* @return 结果 * @return 结果
*/ */
@Override @Override
@Transactional @Transactional
public int updateRole(SysRole role) public SysRole updateRole(SysRole role) {
{ return sysRoleRepository.save(role);
// 修改角色信息
roleMapper.updateRole(role);
// 删除角色与菜单关联
roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
return insertRoleMenu(role);
} }
/** /**
* 修改数据权限信息 * 修改数据权限信息
*
* @param role 角色信息 * @param role 角色信息
* @return 结果 * @return 结果
*/ */
@Override @Override
@Transactional @Transactional
public int authDataScope(SysRole role) public int authDataScope(SysRole role) {
{ SysRole db = sysRoleRepository.findById(role.getRoleId()).get();
// 修改角色信息 db.setDataScope(role.getDataScope());
roleMapper.updateRole(role); db.setDepts(role.getDepts());
// 删除角色与部门关联 return 1;
roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
// 新增角色和部门信息数据权限
return insertRoleDept(role);
}
/**
* 新增角色菜单信息
*
* @param role 角色对象
*/
public int insertRoleMenu(SysRole role)
{
int rows = 1;
// 新增用户与角色管理
List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
for (Long menuId : role.getMenuIds())
{
SysRoleMenu rm = new SysRoleMenu();
rm.setRoleId(role.getRoleId());
rm.setMenuId(menuId);
list.add(rm);
}
if (list.size() > 0)
{
rows = roleMenuMapper.batchRoleMenu(list);
}
return rows;
}
/**
* 新增角色部门信息(数据权限)
*
* @param role 角色对象
*/
public int insertRoleDept(SysRole role)
{
int rows = 1;
// 新增角色与部门数据权限管理
List<SysRoleDept> list = new ArrayList<SysRoleDept>();
for (Long deptId : role.getDeptIds())
{
SysRoleDept rd = new SysRoleDept();
rd.setRoleId(role.getRoleId());
rd.setDeptId(deptId);
list.add(rd);
}
if (list.size() > 0)
{
rows = roleDeptMapper.batchRoleDept(list);
}
return rows;
} }
/** /**
@ -265,12 +204,10 @@ public class SysRoleServiceImpl implements ISysRoleService
* @return 结果 * @return 结果
*/ */
@Override @Override
public String checkRoleNameUnique(SysRole role) public String checkRoleNameUnique(SysRole role) {
{
Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName()); SysRole info = sysRoleRepository.findFirstByRoleName(role.getRoleName());
if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
{
return UserConstants.ROLE_NAME_NOT_UNIQUE; return UserConstants.ROLE_NAME_NOT_UNIQUE;
} }
return UserConstants.ROLE_NAME_UNIQUE; return UserConstants.ROLE_NAME_UNIQUE;
@ -283,12 +220,10 @@ public class SysRoleServiceImpl implements ISysRoleService
* @return 结果 * @return 结果
*/ */
@Override @Override
public String checkRoleKeyUnique(SysRole role) public String checkRoleKeyUnique(SysRole role) {
{
Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey()); SysRole info = sysRoleRepository.findFirstByRoleKey(role.getRoleKey());
if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
{
return UserConstants.ROLE_KEY_NOT_UNIQUE; return UserConstants.ROLE_KEY_NOT_UNIQUE;
} }
return UserConstants.ROLE_KEY_UNIQUE; return UserConstants.ROLE_KEY_UNIQUE;
@ -299,11 +234,8 @@ public class SysRoleServiceImpl implements ISysRoleService
* *
* @param role 角色信息 * @param role 角色信息
*/ */
@Override public void checkRoleAllowed(SysRole role) {
public void checkRoleAllowed(SysRole role) if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) {
{
if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin())
{
throw new BusinessException("不允许操作超级管理员角色"); throw new BusinessException("不允许操作超级管理员角色");
} }
} }
@ -315,9 +247,8 @@ public class SysRoleServiceImpl implements ISysRoleService
* @return 结果 * @return 结果
*/ */
@Override @Override
public int countUserRoleByRoleId(Long roleId) public int countUserRoleByRoleId(Long roleId) {
{ return sysUserRepository.countByRolesContaining(new SysRole(roleId));
return userRoleMapper.countUserRoleByRoleId(roleId);
} }
/** /**
@ -327,9 +258,9 @@ public class SysRoleServiceImpl implements ISysRoleService
* @return 结果 * @return 结果
*/ */
@Override @Override
public int changeStatus(SysRole role) public int changeStatus(SysRole role) {
{ sysRoleRepository.updateStatus(role.getStatus(), role.getRoleId());
return roleMapper.updateRole(role); return 1;
} }
/** /**
@ -338,45 +269,47 @@ public class SysRoleServiceImpl implements ISysRoleService
* @param userRole 用户和角色关联信息 * @param userRole 用户和角色关联信息
* @return 结果 * @return 结果
*/ */
@Transactional
@Override @Override
public int deleteAuthUser(SysUserRole userRole) public int deleteAuthUser(SysUserRole userRole) {
{ SysUser sysUser = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userRole.getUserId());
return userRoleMapper.deleteUserRoleInfo(userRole); Set<SysRole> roles = sysUser.getRoles();
roles.remove(new SysRole(userRole.getRoleId()));
return 1;
} }
/** /**
* 批量取消授权用户角色 * 批量取消授权用户角色
* *
* @param roleId 角色ID * @param roleId 角色ID
* @param userIds 需要删除的用户数据ID * @param userIds 需要删除的用户数据ID
* @return 结果 * @return 结果
*/ */
@Override public int deleteAuthUsers(Long roleId, String userIds) {
public int deleteAuthUsers(Long roleId, String userIds) SysRole sysRole = sysRoleRepository.findById(roleId).get();
{ Long[] users = Convert.toLongArray(userIds);
return userRoleMapper.deleteUserRoleInfos(roleId, Convert.toLongArray(userIds)); for (Long userId : users) {
SysUser sysUser = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId);
sysUser.getRoles().remove(sysRole);
}
return 1;
} }
/** /**
* 批量选择授权用户角色 * 批量选择授权用户角色
* *
* @param roleId 角色ID * @param roleId 角色ID
* @param userIds 需要删除的用户数据ID * @param userIds 需要删除的用户数据ID
* @return 结果 * @return 结果
*/ */
@Override @Transactional
public int insertAuthUsers(Long roleId, String userIds) public int insertAuthUsers(Long roleId, String userIds) {
{ SysRole sysRole = sysRoleRepository.findById(roleId).get();
Long[] users = Convert.toLongArray(userIds); Long[] users = Convert.toLongArray(userIds);
// 新增用户与角色管理 for (Long userId : users) {
List<SysUserRole> list = new ArrayList<SysUserRole>(); SysUser sysUser = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId);
for (Long userId : users) sysUser.getRoles().add(sysRole);
{
SysUserRole ur = new SysUserRole();
ur.setUserId(userId);
ur.setRoleId(roleId);
list.add(ur);
} }
return userRoleMapper.batchUserRole(list); return 1;
} }
} }

View File

@ -1,30 +1,37 @@
package com.ruoyi.system.service.impl; package com.ruoyi.system.service.impl;
import java.util.ArrayList; import com.querydsl.core.types.ExpressionUtils;
import java.util.List; import com.ruoyi.common.base.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.Md5Utils; import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.system.domain.SysPost; import com.ruoyi.system.domain.QSysUser;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysRole; import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.SysUserPost; import com.ruoyi.system.repository.SysRoleRepository;
import com.ruoyi.system.domain.SysUserRole; import com.ruoyi.system.repository.SysUserRepository;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService; import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;
import java.util.stream.Collectors;
/** /**
* 用户 业务层处理 * 用户 业务层处理
@ -32,65 +39,128 @@ import com.ruoyi.system.service.ISysUserService;
* @author ruoyi * @author ruoyi
*/ */
@Service @Service
public class SysUserServiceImpl implements ISysUserService public class SysUserServiceImpl extends BaseService implements ISysUserService {
{
private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class); private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
@Autowired @Autowired
private SysUserMapper userMapper; private SysUserRepository sysUserRepository;
@Autowired
private SysRoleMapper roleMapper;
@Autowired
private SysPostMapper postMapper;
@Autowired
private SysUserPostMapper userPostMapper;
@Autowired
private SysUserRoleMapper userRoleMapper;
@Autowired @Autowired
private ISysConfigService configService; private ISysConfigService configService;
@Autowired
private SysRoleRepository sysRoleRepository;
/** /**
* 根据条件分页查询用户列表 * 根据条件分页查询用户列表
* *
* @param user 用户信息 * @param user 用户信息
* @param pageRequest
* @return 用户信息集合信息 * @return 用户信息集合信息
*/ */
@Override @Override
@DataScope(deptAlias = "d", userAlias = "u") public Page<SysUser> selectUserList(SysUser user, Pageable pageRequest) {
public List<SysUser> selectUserList(SysUser user) return sysUserRepository.findAll(getPredicate(user), pageRequest);
{ }
return userMapper.selectUserList(user);
private com.querydsl.core.types.Predicate getPredicate(SysUser sysUser){
QSysUser qSysUser = QSysUser.sysUser;
List<com.querydsl.core.types.Predicate> predicates = new ArrayList<>();
if(StringUtils.isNotEmpty(sysUser.getDelFlag())){
predicates.add(qSysUser.delFlag.eq(sysUser.getDelFlag()));
}
if(StringUtils.isNotEmpty(sysUser.getLoginName())){
predicates.add(buildLike(qSysUser.loginName, sysUser.getLoginName()));
}
if(StringUtils.isNotEmpty(sysUser.getStatus())){
predicates.add(buildEqual(qSysUser.status, sysUser.getStatus()));
}
if(StringUtils.isNotEmpty(sysUser.getPhonenumber())){
predicates.add(buildLike(qSysUser.phonenumber, sysUser.getPhonenumber()));
}
if(sysUser.getStartTime() != null){
predicates.add(buildGreaterThanOrEqualTo(qSysUser.createTime, sysUser.getStartTime()));
}
if(sysUser.getEndTime() != null){
predicates.add(buildLessThanOrEqualTo(qSysUser.createTime, sysUser.getEndTime()));
}
if(sysUser.getDept() != null && sysUser.getDept().getDeptId() != null){
predicates.add(buildEqual(qSysUser.dept.deptId, sysUser.getDept().getDeptId()));
}
if(sysUser.getDept() != null && StringUtils.isNotEmpty(sysUser.getDept().getCode())){
predicates.add(buildLike(qSysUser.dept.code, sysUser.getDept().getCode()));
}
return ExpressionUtils.allOf(predicates);
}
private Specification<SysUser> getSpecification(SysUser sysUser){
return new Specification<SysUser>() {
@Override
public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
if(StringUtils.isNotEmpty(sysUser.getDelFlag())){
predicates.add(criteriaBuilder.equal(root.get("delFlag").as(String.class), sysUser.getDelFlag()));
}
if(StringUtils.isNotEmpty(sysUser.getLoginName())){
predicates.add(criteriaBuilder.like(root.get("loginName").as(String.class), "%" + sysUser.getLoginName() + "%"));
}
if(StringUtils.isNotEmpty(sysUser.getStatus())){
predicates.add(criteriaBuilder.equal(root.get("status").as(String.class), sysUser.getStatus()));
}
if(StringUtils.isNotEmpty(sysUser.getPhonenumber())){
predicates.add(criteriaBuilder.like(root.get("phonenumber").as(String.class), "%" + sysUser.getPhonenumber() + "%"));
}
if(sysUser.getStartTime() != null){
predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime").as(Date.class), sysUser.getStartTime()));
}
if(sysUser.getEndTime() != null){
predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("endTime").as(Date.class), sysUser.getEndTime()));
}
if(sysUser.getDept() != null && sysUser.getDept().getDeptId() != null){
predicates.add(criteriaBuilder.equal(root.get("dept").get("deptId").as(Long.class), sysUser.getDept().getDeptId()));
}
if(sysUser.getDept() != null && StringUtils.isNotEmpty(sysUser.getDept().getCode())){
predicates.add(criteriaBuilder.equal(root.get("dept").get("code").as(String.class), "%" + sysUser.getDept().getCode() + "%"));
}
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
} }
/** /**
* 根据条件分页查询已分配用户角色列表 * 根据条件分页查询已分配用户角色列表
* *
* @param user 用户信息 * @param user 用户信息
* @param pageRequest
* @return 用户信息集合信息 * @return 用户信息集合信息
*/ */
@Override public Page<SysUser> selectAllocatedList(SysUser user, Pageable pageRequest) {
@DataScope(deptAlias = "d", userAlias = "u") return sysUserRepository.findAll(getSpecification(user), pageRequest);
public List<SysUser> selectAllocatedList(SysUser user)
{
return userMapper.selectAllocatedList(user);
} }
/** /**
* 根据条件分页查询未分配用户角色列表 * 根据条件分页查询未分配用户角色列表
* *
* @param user 用户信息 * @param sysUser 用户信息
* @return 用户信息集合信息 * @return 用户信息集合信息
*/ */
@Override public Page<SysUser> selectUnallocatedList(SysUser sysUser, Pageable pageable) {
@DataScope(deptAlias = "d", userAlias = "u") return sysUserRepository.findAll(new Specification<SysUser>() {
public List<SysUser> selectUnallocatedList(SysUser user) @Override
{ public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
return userMapper.selectUnallocatedList(user); List<Predicate> predicates = new ArrayList<>();
if(StringUtils.isNotEmpty(sysUser.getLoginName())){
predicates.add(criteriaBuilder.like(root.get("loginName").as(String.class), "%" + sysUser.getLoginName() + "%"));
}
if(StringUtils.isNotEmpty(sysUser.getPhonenumber())){
predicates.add(criteriaBuilder.like(root.get("phonenumber").as(String.class), "%" + sysUser.getPhonenumber() + "%"));
}
if(sysUser.getRoles() != null && sysUser.getRoles().size() == 1){
SysRole role = sysUser.getRoles().iterator().next();
Predicate notMember = criteriaBuilder.isNotMember(role, root.get("roles").as(Set.class));
predicates.add(notMember);
}
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
}, pageable);
} }
/** /**
@ -100,9 +170,8 @@ public class SysUserServiceImpl implements ISysUserService
* @return 用户对象信息 * @return 用户对象信息
*/ */
@Override @Override
public SysUser selectUserByLoginName(String userName) public SysUser selectUserByLoginName(String userName) {
{ return sysUserRepository.findFirstByDelFlagAndLoginName(BaseEntity.NOT_DELETED, userName);
return userMapper.selectUserByLoginName(userName);
} }
/** /**
@ -112,9 +181,8 @@ public class SysUserServiceImpl implements ISysUserService
* @return 用户对象信息 * @return 用户对象信息
*/ */
@Override @Override
public SysUser selectUserByPhoneNumber(String phoneNumber) public SysUser selectUserByPhoneNumber(String phoneNumber) {
{ return sysUserRepository.findFirstByDelFlagAndAndPhonenumber(BaseEntity.NOT_DELETED, phoneNumber);
return userMapper.selectUserByPhoneNumber(phoneNumber);
} }
/** /**
@ -124,9 +192,8 @@ public class SysUserServiceImpl implements ISysUserService
* @return 用户对象信息 * @return 用户对象信息
*/ */
@Override @Override
public SysUser selectUserByEmail(String email) public SysUser selectUserByEmail(String email) {
{ return sysUserRepository.findFirstByDelFlagAndEmail(BaseEntity.NOT_DELETED, email);
return userMapper.selectUserByEmail(email);
} }
/** /**
@ -136,21 +203,13 @@ public class SysUserServiceImpl implements ISysUserService
* @return 用户对象信息 * @return 用户对象信息
*/ */
@Override @Override
public SysUser selectUserById(Long userId) public SysUser selectUserById(Long userId) {
{ return sysUserRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException("无效的数据"));
return userMapper.selectUserById(userId);
} }
/**
* 通过用户ID查询用户和角色关联
*
* @param userId 用户ID
* @return 用户和角色关联列表
*/
@Override @Override
public List<SysUserRole> selectUserRoleByUserId(Long userId) public SysUser selectUserWithRolesAndPostsById(Long userId) {
{ return sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId);
return userRoleMapper.selectUserRoleByUserId(userId);
} }
/** /**
@ -159,14 +218,11 @@ public class SysUserServiceImpl implements ISysUserService
* @param userId 用户ID * @param userId 用户ID
* @return 结果 * @return 结果
*/ */
@Transactional
@Override @Override
public int deleteUserById(Long userId) public int deleteUserById(Long userId) {
{ sysUserRepository.deleteById(userId);
// 删除用户与角色关联 return 1;
userRoleMapper.deleteUserRoleByUserId(userId);
// 删除用户与岗位表
userPostMapper.deleteUserPostByUserId(userId);
return userMapper.deleteUserById(userId);
} }
/** /**
@ -175,15 +231,15 @@ public class SysUserServiceImpl implements ISysUserService
* @param ids 需要删除的数据ID * @param ids 需要删除的数据ID
* @return 结果 * @return 结果
*/ */
@Transactional
@Override @Override
public int deleteUserByIds(String ids) throws BusinessException public int deleteUserByIds(String ids) throws BusinessException {
{
Long[] userIds = Convert.toLongArray(ids); Long[] userIds = Convert.toLongArray(ids);
for (Long userId : userIds) for (Long userId : userIds) {
{
checkUserAllowed(new SysUser(userId)); checkUserAllowed(new SysUser(userId));
deleteUserById(userId);
} }
return userMapper.deleteUserByIds(userIds); return userIds.length;
} }
/** /**
@ -194,28 +250,8 @@ public class SysUserServiceImpl implements ISysUserService
*/ */
@Override @Override
@Transactional @Transactional
public int insertUser(SysUser user) public SysUser insertUser(SysUser user) {
{ return sysUserRepository.save(user);
// 新增用户信息
int rows = userMapper.insertUser(user);
// 新增用户岗位关联
insertUserPost(user);
// 新增用户与角色管理
insertUserRole(user.getUserId(), user.getRoleIds());
return rows;
}
/**
* 注册用户信息
*
* @param user 用户信息
* @return 结果
*/
@Override
public boolean registerUser(SysUser user)
{
user.setUserType(UserConstants.REGISTER_USER_TYPE);
return userMapper.insertUser(user) > 0;
} }
/** /**
@ -226,18 +262,10 @@ public class SysUserServiceImpl implements ISysUserService
*/ */
@Override @Override
@Transactional @Transactional
public int updateUser(SysUser user) public SysUser updateUser(SysUser user) {
{ SysUser db = sysUserRepository.findById(user.getUserId()).get();
Long userId = user.getUserId(); BeanUtils.copyProperties(user, db, "delFlag", "loginDate", "loginIp", "salt", "password", "avatar");
// 删除用户与角色关联 return sysUserRepository.save(db);
userRoleMapper.deleteUserRoleByUserId(userId);
// 新增用户与角色管理
insertUserRole(user.getUserId(), user.getRoleIds());
// 删除用户与岗位关联
userPostMapper.deleteUserPostByUserId(userId);
// 新增用户与岗位管理
insertUserPost(user);
return userMapper.updateUser(user);
} }
/** /**
@ -247,22 +275,8 @@ public class SysUserServiceImpl implements ISysUserService
* @return 结果 * @return 结果
*/ */
@Override @Override
public int updateUserInfo(SysUser user) public SysUser updateUserInfo(SysUser user) {
{ return sysUserRepository.save(user);
return userMapper.updateUser(user);
}
/**
* 用户授权角色
*
* @param userId 用户ID
* @param roleIds 角色组
*/
@Override
public void insertUserAuth(Long userId, Long[] roleIds)
{
userRoleMapper.deleteUserRoleByUserId(userId);
insertUserRole(userId, roleIds);
} }
/** /**
@ -271,61 +285,13 @@ public class SysUserServiceImpl implements ISysUserService
* @param user 用户信息 * @param user 用户信息
* @return 结果 * @return 结果
*/ */
@Transactional
@Override @Override
public int resetUserPwd(SysUser user) public SysUser resetUserPwd(SysUser user) {
{ SysUser db = sysUserRepository.findById(user.getUserId()).get();
return updateUserInfo(user); db.setSalt(user.getSalt());
} db.setPassword(user.getPassword());
return db;
/**
* 新增用户角色信息
*
* @param user 用户对象
*/
public void insertUserRole(Long userId, Long[] roleIds)
{
if (StringUtils.isNotNull(roleIds))
{
// 新增用户与角色管理
List<SysUserRole> list = new ArrayList<SysUserRole>();
for (Long roleId : roleIds)
{
SysUserRole ur = new SysUserRole();
ur.setUserId(userId);
ur.setRoleId(roleId);
list.add(ur);
}
if (list.size() > 0)
{
userRoleMapper.batchUserRole(list);
}
}
}
/**
* 新增用户岗位信息
*
* @param user 用户对象
*/
public void insertUserPost(SysUser user)
{
Long[] posts = user.getPostIds();
if (StringUtils.isNotNull(posts))
{
// 新增用户与岗位管理
List<SysUserPost> list = new ArrayList<SysUserPost>();
for (Long postId : posts)
{
SysUserPost up = new SysUserPost();
up.setUserId(user.getUserId());
up.setPostId(postId);
list.add(up);
}
if (list.size() > 0)
{
userPostMapper.batchUserPost(list);
}
}
} }
/** /**
@ -335,29 +301,25 @@ public class SysUserServiceImpl implements ISysUserService
* @return * @return
*/ */
@Override @Override
public String checkLoginNameUnique(String loginName) public String checkLoginNameUnique(String loginName) {
{ int count = sysUserRepository.countByLoginName(loginName);
int count = userMapper.checkLoginNameUnique(loginName); if (count > 0) {
if (count > 0)
{
return UserConstants.USER_NAME_NOT_UNIQUE; return UserConstants.USER_NAME_NOT_UNIQUE;
} }
return UserConstants.USER_NAME_UNIQUE; return UserConstants.USER_NAME_UNIQUE;
} }
/** /**
* 校验手机号码是否唯一 * 校验用户名称是否唯一
* *
* @param user 用户信息 * @param user 用户信息
* @return * @return
*/ */
@Override @Override
public String checkPhoneUnique(SysUser user) public String checkPhoneUnique(SysUser user) {
{
Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId(); Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber()); SysUser info = sysUserRepository.findFirstByPhonenumber(user.getPhonenumber());
if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
{
return UserConstants.USER_PHONE_NOT_UNIQUE; return UserConstants.USER_PHONE_NOT_UNIQUE;
} }
return UserConstants.USER_PHONE_UNIQUE; return UserConstants.USER_PHONE_UNIQUE;
@ -370,12 +332,10 @@ public class SysUserServiceImpl implements ISysUserService
* @return * @return
*/ */
@Override @Override
public String checkEmailUnique(SysUser user) public String checkEmailUnique(SysUser user) {
{
Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId(); Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
SysUser info = userMapper.checkEmailUnique(user.getEmail()); SysUser info = sysUserRepository.findFirstByEmail(user.getEmail());
if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
{
return UserConstants.USER_EMAIL_NOT_UNIQUE; return UserConstants.USER_EMAIL_NOT_UNIQUE;
} }
return UserConstants.USER_EMAIL_UNIQUE; return UserConstants.USER_EMAIL_UNIQUE;
@ -386,72 +346,23 @@ public class SysUserServiceImpl implements ISysUserService
* *
* @param user 用户信息 * @param user 用户信息
*/ */
@Override public void checkUserAllowed(SysUser user) {
public void checkUserAllowed(SysUser user) if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
{
if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
{
throw new BusinessException("不允许操作超级管理员用户"); throw new BusinessException("不允许操作超级管理员用户");
} }
} }
/**
* 查询用户所属角色组
*
* @param userId 用户ID
* @return 结果
*/
@Override
public String selectUserRoleGroup(Long userId)
{
List<SysRole> list = roleMapper.selectRolesByUserId(userId);
StringBuffer idsStr = new StringBuffer();
for (SysRole role : list)
{
idsStr.append(role.getRoleName()).append(",");
}
if (StringUtils.isNotEmpty(idsStr.toString()))
{
return idsStr.substring(0, idsStr.length() - 1);
}
return idsStr.toString();
}
/**
* 查询用户所属岗位组
*
* @param userId 用户ID
* @return 结果
*/
@Override
public String selectUserPostGroup(Long userId)
{
List<SysPost> list = postMapper.selectPostsByUserId(userId);
StringBuffer idsStr = new StringBuffer();
for (SysPost post : list)
{
idsStr.append(post.getPostName()).append(",");
}
if (StringUtils.isNotEmpty(idsStr.toString()))
{
return idsStr.substring(0, idsStr.length() - 1);
}
return idsStr.toString();
}
/** /**
* 导入用户数据 * 导入用户数据
* *
* @param userList 用户数据列表 * @param userList 用户数据列表
* @param isUpdateSupport 是否更新支持如果已存在则进行更新数据 * @param isUpdateSupport 是否更新支持如果已存在则进行更新数据
* @param operName 操作用户 * @param operName 操作用户
* @return 结果 * @return 结果
*/ */
@Override @Override
public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
{ if (StringUtils.isNull(userList) || userList.size() == 0) {
if (StringUtils.isNull(userList) || userList.size() == 0)
{
throw new BusinessException("导入用户数据不能为空!"); throw new BusinessException("导入用户数据不能为空!");
} }
int successNum = 0; int successNum = 0;
@ -459,48 +370,36 @@ public class SysUserServiceImpl implements ISysUserService
StringBuilder successMsg = new StringBuilder(); StringBuilder successMsg = new StringBuilder();
StringBuilder failureMsg = new StringBuilder(); StringBuilder failureMsg = new StringBuilder();
String password = configService.selectConfigByKey("sys.user.initPassword"); String password = configService.selectConfigByKey("sys.user.initPassword");
for (SysUser user : userList) for (SysUser user : userList) {
{ try {
try
{
// 验证是否存在这个用户 // 验证是否存在这个用户
SysUser u = userMapper.selectUserByLoginName(user.getLoginName()); SysUser u = sysUserRepository.findFirstByLoginName(user.getLoginName());
if (StringUtils.isNull(u)) if (StringUtils.isNull(u)) {
{
user.setPassword(Md5Utils.hash(user.getLoginName() + password)); user.setPassword(Md5Utils.hash(user.getLoginName() + password));
user.setCreateBy(operName); user.setCreateBy(operName);
this.insertUser(user); this.insertUser(user);
successNum++; successNum++;
successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 导入成功"); successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 导入成功");
} } else if (isUpdateSupport) {
else if (isUpdateSupport)
{
user.setUpdateBy(operName); user.setUpdateBy(operName);
this.updateUser(user); this.updateUser(user);
successNum++; successNum++;
successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 更新成功"); successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 更新成功");
} } else {
else
{
failureNum++; failureNum++;
failureMsg.append("<br/>" + failureNum + "、账号 " + user.getLoginName() + " 已存在"); failureMsg.append("<br/>" + failureNum + "、账号 " + user.getLoginName() + " 已存在");
} }
} } catch (Exception e) {
catch (Exception e)
{
failureNum++; failureNum++;
String msg = "<br/>" + failureNum + "、账号 " + user.getLoginName() + " 导入失败:"; String msg = "<br/>" + failureNum + "、账号 " + user.getLoginName() + " 导入失败:";
failureMsg.append(msg + e.getMessage()); failureMsg.append(msg + e.getMessage());
log.error(msg, e); log.error(msg, e);
} }
} }
if (failureNum > 0) if (failureNum > 0) {
{
failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:"); failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:");
throw new BusinessException(failureMsg.toString()); throw new BusinessException(failureMsg.toString());
} } else {
else
{
successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:");
} }
return successMsg.toString(); return successMsg.toString();
@ -513,8 +412,35 @@ public class SysUserServiceImpl implements ISysUserService
* @return 结果 * @return 结果
*/ */
@Override @Override
public int changeStatus(SysUser user) public void changeStatus(SysUser user) {
{ sysUserRepository.changeStatus(user.getStatus(), user.getUserId());
return userMapper.updateUser(user); }
public Set<SysDept> getUserRoleDepts(Long userId){
SysUser user = sysUserRepository.findSysUserByDelFlagAndUserId(BaseEntity.NOT_DELETED, userId);
Set<SysDept> depts = new HashSet<>();
Set<SysRole> roles = user.getRoles();
for(SysRole sysRole : roles){
sysRole = sysRoleRepository.findByRoleId(sysRole.getRoleId());
depts.addAll(sysRole.getDepts());
}
return depts;
}
@Override
public SysUser registerUser(SysUser user) {
user.setUserType(UserConstants.REGISTER_USER_TYPE);
return sysUserRepository.save(user);
}
@Transactional
@Override
public void insertUserAuth(Long userId, Long[] roleIds) {
SysUser sysUser = sysUserRepository.findById(userId).get();
Set<SysRole> roles = Arrays.stream(roleIds)
.map(roleId -> new SysRole(roleId))
.collect(Collectors.toSet());
sysUser.setRoles(roles);
sysUserRepository.save(sysUser);
} }
} }

View File

@ -1,6 +1,7 @@
package com.ruoyi.system.utils; package com.ruoyi.system.utils;
import java.util.List; import java.util.List;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.CacheUtils; import com.ruoyi.common.utils.CacheUtils;
@ -13,8 +14,7 @@ import com.ruoyi.system.domain.SysDictData;
* @author ruoyi * @author ruoyi
*/ */
@Component @Component
public class DictUtils public class DictUtils {
{
/** /**
* 分隔符 * 分隔符
*/ */
@ -23,11 +23,10 @@ public class DictUtils
/** /**
* 设置字典缓存 * 设置字典缓存
* *
* @param key 参数键 * @param key 参数键
* @param dictDatas 字典数据列表 * @param dictDatas 字典数据列表
*/ */
public static void setDictCache(String key, List<SysDictData> dictDatas) public static void setDictCache(String key, List<SysDictData> dictDatas) {
{
CacheUtils.put(getCacheName(), getCacheKey(key), dictDatas); CacheUtils.put(getCacheName(), getCacheKey(key), dictDatas);
} }
@ -37,11 +36,9 @@ public class DictUtils
* @param key 参数键 * @param key 参数键
* @return dictDatas 字典数据列表 * @return dictDatas 字典数据列表
*/ */
public static List<SysDictData> getDictCache(String key) public static List<SysDictData> getDictCache(String key) {
{
Object cacheObj = CacheUtils.get(getCacheName(), getCacheKey(key)); Object cacheObj = CacheUtils.get(getCacheName(), getCacheKey(key));
if (StringUtils.isNotNull(cacheObj)) if (StringUtils.isNotNull(cacheObj)) {
{
List<SysDictData> DictDatas = StringUtils.cast(cacheObj); List<SysDictData> DictDatas = StringUtils.cast(cacheObj);
return DictDatas; return DictDatas;
} }
@ -51,60 +48,49 @@ public class DictUtils
/** /**
* 根据字典类型和字典值获取字典标签 * 根据字典类型和字典值获取字典标签
* *
* @param dictType 字典类型 * @param dictType 字典类型
* @param dictValue 字典值 * @param dictValue 字典值
* @return 字典标签 * @return 字典标签
*/ */
public static String getDictLabel(String dictType, String dictValue) public static String getDictLabel(String dictType, String dictValue) {
{
return getDictLabel(dictType, dictValue, SEPARATOR); return getDictLabel(dictType, dictValue, SEPARATOR);
} }
/** /**
* 根据字典类型和字典标签获取字典值 * 根据字典类型和字典标签获取字典值
* *
* @param dictType 字典类型 * @param dictType 字典类型
* @param dictLabel 字典标签 * @param dictLabel 字典标签
* @return 字典值 * @return 字典值
*/ */
public static String getDictValue(String dictType, String dictLabel) public static String getDictValue(String dictType, String dictLabel) {
{
return getDictValue(dictType, dictLabel, SEPARATOR); return getDictValue(dictType, dictLabel, SEPARATOR);
} }
/** /**
* 根据字典类型和字典值获取字典标签 * 根据字典类型和字典值获取字典标签
* *
* @param dictType 字典类型 * @param dictType 字典类型
* @param dictValue 字典值 * @param dictValue 字典值
* @param separator 分隔符 * @param separator 分隔符
* @return 字典标签 * @return 字典标签
*/ */
public static String getDictLabel(String dictType, String dictValue, String separator) public static String getDictLabel(String dictType, String dictValue, String separator) {
{
StringBuilder propertyString = new StringBuilder(); StringBuilder propertyString = new StringBuilder();
List<SysDictData> datas = getDictCache(dictType); List<SysDictData> datas = getDictCache(dictType);
if (StringUtils.containsAny(separator, dictValue) && StringUtils.isNotEmpty(datas)) if (StringUtils.containsAny(separator, dictValue) && StringUtils.isNotEmpty(datas)) {
{ for (SysDictData dict : datas) {
for (SysDictData dict : datas) for (String value : dictValue.split(separator)) {
{ if (value.equals(dict.getDictValue())) {
for (String value : dictValue.split(separator))
{
if (value.equals(dict.getDictValue()))
{
propertyString.append(dict.getDictLabel() + separator); propertyString.append(dict.getDictLabel() + separator);
break; break;
} }
} }
} }
} } else {
else for (SysDictData dict : datas) {
{ if (dictValue.equals(dict.getDictValue())) {
for (SysDictData dict : datas)
{
if (dictValue.equals(dict.getDictValue()))
{
return dict.getDictLabel(); return dict.getDictLabel();
} }
} }
@ -115,36 +101,27 @@ public class DictUtils
/** /**
* 根据字典类型和字典标签获取字典值 * 根据字典类型和字典标签获取字典值
* *
* @param dictType 字典类型 * @param dictType 字典类型
* @param dictLabel 字典标签 * @param dictLabel 字典标签
* @param separator 分隔符 * @param separator 分隔符
* @return 字典值 * @return 字典值
*/ */
public static String getDictValue(String dictType, String dictLabel, String separator) public static String getDictValue(String dictType, String dictLabel, String separator) {
{
StringBuilder propertyString = new StringBuilder(); StringBuilder propertyString = new StringBuilder();
List<SysDictData> datas = getDictCache(dictType); List<SysDictData> datas = getDictCache(dictType);
if (StringUtils.containsAny(separator, dictLabel) && StringUtils.isNotEmpty(datas)) if (StringUtils.containsAny(separator, dictLabel) && StringUtils.isNotEmpty(datas)) {
{ for (SysDictData dict : datas) {
for (SysDictData dict : datas) for (String label : dictLabel.split(separator)) {
{ if (label.equals(dict.getDictLabel())) {
for (String label : dictLabel.split(separator))
{
if (label.equals(dict.getDictLabel()))
{
propertyString.append(dict.getDictValue() + separator); propertyString.append(dict.getDictValue() + separator);
break; break;
} }
} }
} }
} } else {
else for (SysDictData dict : datas) {
{ if (dictLabel.equals(dict.getDictLabel())) {
for (SysDictData dict : datas)
{
if (dictLabel.equals(dict.getDictLabel()))
{
return dict.getDictValue(); return dict.getDictValue();
} }
} }
@ -155,8 +132,7 @@ public class DictUtils
/** /**
* 清空字典缓存 * 清空字典缓存
*/ */
public static void clearDictCache() public static void clearDictCache() {
{
CacheUtils.removeAll(getCacheName()); CacheUtils.removeAll(getCacheName());
} }
@ -165,8 +141,7 @@ public class DictUtils
* *
* @return 缓存名 * @return 缓存名
*/ */
public static String getCacheName() public static String getCacheName() {
{
return Constants.SYS_DICT_CACHE; return Constants.SYS_DICT_CACHE;
} }
@ -176,8 +151,7 @@ public class DictUtils
* @param configKey 参数键 * @param configKey 参数键
* @return 缓存键key * @return 缓存键key
*/ */
public static String getCacheKey(String configKey) public static String getCacheKey(String configKey) {
{
return Constants.SYS_DICT_KEY + configKey; return Constants.SYS_DICT_KEY + configKey;
} }
} }

View File

@ -1,108 +0,0 @@
<?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.ruoyi.system.mapper.SysConfigMapper">
<resultMap type="SysConfig" id="SysConfigResult">
<id property="configId" column="config_id" />
<result property="configName" column="config_name" />
<result property="configKey" column="config_key" />
<result property="configValue" column="config_value" />
<result property="configType" column="config_type" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
</resultMap>
<sql id="selectConfigVo">
select config_id, config_name, config_key, config_value, config_type, create_by, create_time, update_by, update_time, remark
from sys_config
</sql>
<!-- 查询条件 -->
<sql id="sqlwhereSearch">
<where>
<if test="configId !=null">
and config_id = #{configId}
</if>
<if test="configKey !=null and configKey != ''">
and config_key = #{configKey}
</if>
</where>
</sql>
<select id="selectConfig" parameterType="SysConfig" resultMap="SysConfigResult">
<include refid="selectConfigVo"/>
<include refid="sqlwhereSearch"/>
</select>
<select id="selectConfigList" parameterType="SysConfig" resultMap="SysConfigResult">
<include refid="selectConfigVo"/>
<where>
<if test="configName != null and configName != ''">
AND config_name like concat('%', #{configName}, '%')
</if>
<if test="configType != null and configType != ''">
AND config_type = #{configType}
</if>
<if test="configKey != null and configKey != ''">
AND config_key like concat('%', #{configKey}, '%')
</if>
<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
and date_format(create_time,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
</if>
<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
and date_format(create_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
</if>
</where>
</select>
<select id="checkConfigKeyUnique" parameterType="String" resultMap="SysConfigResult">
<include refid="selectConfigVo"/>
where config_key = #{configKey} limit 1
</select>
<insert id="insertConfig" parameterType="SysConfig">
insert into sys_config (
<if test="configName != null and configName != '' ">config_name,</if>
<if test="configKey != null and configKey != '' ">config_key,</if>
<if test="configValue != null and configValue != '' ">config_value,</if>
<if test="configType != null and configType != '' ">config_type,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
<if test="remark != null and remark != ''">remark,</if>
create_time
)values(
<if test="configName != null and configName != ''">#{configName},</if>
<if test="configKey != null and configKey != ''">#{configKey},</if>
<if test="configValue != null and configValue != ''">#{configValue},</if>
<if test="configType != null and configType != ''">#{configType},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
<if test="remark != null and remark != ''">#{remark},</if>
sysdate()
)
</insert>
<update id="updateConfig" parameterType="SysConfig">
update sys_config
<set>
<if test="configName != null and configName != ''">config_name = #{configName},</if>
<if test="configKey != null and configKey != ''">config_key = #{configKey},</if>
<if test="configValue != null and configValue != ''">config_value = #{configValue},</if>
<if test="configType != null and configType != ''">config_type = #{configType},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
<if test="remark != null">remark = #{remark},</if>
update_time = sysdate()
</set>
where config_id = #{configId}
</update>
<delete id="deleteConfigByIds" parameterType="String">
delete from sys_config where config_id in
<foreach item="configId" collection="array" open="(" separator="," close=")">
#{configId}
</foreach>
</delete>
</mapper>

View File

@ -1,158 +0,0 @@
<?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.ruoyi.system.mapper.SysDeptMapper">
<resultMap type="SysDept" id="SysDeptResult">
<id property="deptId" column="dept_id" />
<result property="parentId" column="parent_id" />
<result property="ancestors" column="ancestors" />
<result property="deptName" column="dept_name" />
<result property="orderNum" column="order_num" />
<result property="leader" column="leader" />
<result property="phone" column="phone" />
<result property="email" column="email" />
<result property="status" column="status" />
<result property="delFlag" column="del_flag" />
<result property="parentName" column="parent_name" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
</resultMap>
<sql id="selectDeptVo">
select d.dept_id, d.parent_id, d.ancestors, d.dept_name, d.order_num, d.leader, d.phone, d.email, d.status, d.del_flag, d.create_by, d.create_time
from sys_dept d
</sql>
<select id="selectRoleDeptTree" parameterType="Long" resultType="String">
select concat(d.dept_id, d.dept_name) as dept_name
from sys_dept d
left join sys_role_dept rd on d.dept_id = rd.dept_id
where d.del_flag = '0' and rd.role_id = #{roleId}
order by d.parent_id, d.order_num
</select>
<select id="selectDeptList" parameterType="SysDept" resultMap="SysDeptResult">
<include refid="selectDeptVo"/>
where d.del_flag = '0'
<if test="parentId != null and parentId != 0">
AND parent_id = #{parentId}
</if>
<if test="deptName != null and deptName != ''">
AND dept_name like concat('%', #{deptName}, '%')
</if>
<if test="status != null and status != ''">
AND status = #{status}
</if>
<!-- 数据范围过滤 -->
${params.dataScope}
order by d.parent_id, d.order_num
</select>
<select id="checkDeptExistUser" parameterType="Long" resultType="int">
select count(1) from sys_user where dept_id = #{deptId} and del_flag = '0'
</select>
<select id="selectDeptCount" parameterType="SysDept" resultType="int">
select count(1) from sys_dept
where del_flag = '0'
<if test="deptId != null and deptId != 0"> and dept_id = #{deptId} </if>
<if test="parentId != null and parentId != 0"> and parent_id = #{parentId} </if>
</select>
<select id="checkDeptNameUnique" resultMap="SysDeptResult">
<include refid="selectDeptVo"/>
where dept_name=#{deptName} and parent_id = #{parentId} limit 1
</select>
<select id="selectDeptById" parameterType="Long" resultMap="SysDeptResult">
select d.dept_id, d.parent_id, d.ancestors, d.dept_name, d.order_num, d.leader, d.phone, d.email, d.status,
(select dept_name from sys_dept where dept_id = d.parent_id) parent_name
from sys_dept d
where d.dept_id = #{deptId}
</select>
<select id="selectChildrenDeptById" parameterType="Long" resultMap="SysDeptResult">
select * from sys_dept where find_in_set(#{deptId}, ancestors)
</select>
<select id="selectNormalChildrenDeptById" parameterType="Long" resultType="int">
select count(*) from sys_dept where status = 0 and del_flag = '0' and find_in_set(#{deptId}, ancestors)
</select>
<insert id="insertDept" parameterType="SysDept">
insert into sys_dept(
<if test="deptId != null and deptId != 0">dept_id,</if>
<if test="parentId != null and parentId != 0">parent_id,</if>
<if test="deptName != null and deptName != ''">dept_name,</if>
<if test="ancestors != null and ancestors != ''">ancestors,</if>
<if test="orderNum != null and orderNum != ''">order_num,</if>
<if test="leader != null and leader != ''">leader,</if>
<if test="phone != null and phone != ''">phone,</if>
<if test="email != null and email != ''">email,</if>
<if test="status != null">status,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
create_time
)values(
<if test="deptId != null and deptId != 0">#{deptId},</if>
<if test="parentId != null and parentId != 0">#{parentId},</if>
<if test="deptName != null and deptName != ''">#{deptName},</if>
<if test="ancestors != null and ancestors != ''">#{ancestors},</if>
<if test="orderNum != null and orderNum != ''">#{orderNum},</if>
<if test="leader != null and leader != ''">#{leader},</if>
<if test="phone != null and phone != ''">#{phone},</if>
<if test="email != null and email != ''">#{email},</if>
<if test="status != null">#{status},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
sysdate()
)
</insert>
<update id="updateDept" parameterType="SysDept">
update sys_dept
<set>
<if test="parentId != null and parentId != 0">parent_id = #{parentId},</if>
<if test="deptName != null and deptName != ''">dept_name = #{deptName},</if>
<if test="ancestors != null and ancestors != ''">ancestors = #{ancestors},</if>
<if test="orderNum != null and orderNum != ''">order_num = #{orderNum},</if>
<if test="leader != null">leader = #{leader},</if>
<if test="phone != null">phone = #{phone},</if>
<if test="email != null">email = #{email},</if>
<if test="status != null and status != ''">status = #{status},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
update_time = sysdate()
</set>
where dept_id = #{deptId}
</update>
<update id="updateDeptChildren" parameterType="java.util.List">
update sys_dept set ancestors =
<foreach collection="depts" item="item" index="index"
separator=" " open="case dept_id" close="end">
when #{item.deptId} then #{item.ancestors}
</foreach>
where dept_id in
<foreach collection="depts" item="item" index="index"
separator="," open="(" close=")">
#{item.deptId}
</foreach>
</update>
<delete id="deleteDeptById" parameterType="Long">
update sys_dept set del_flag = '2' where dept_id = #{deptId}
</delete>
<update id="updateDeptStatus" parameterType="SysDept">
update sys_dept
<set>
<if test="status != null and status != ''">status = #{status},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
update_time = sysdate()
</set>
where dept_id in (${ancestors})
</update>
</mapper>

View File

@ -1,123 +0,0 @@
<?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.ruoyi.system.mapper.SysDictDataMapper">
<resultMap type="SysDictData" id="SysDictDataResult">
<id property="dictCode" column="dict_code" />
<result property="dictSort" column="dict_sort" />
<result property="dictLabel" column="dict_label" />
<result property="dictValue" column="dict_value" />
<result property="dictType" column="dict_type" />
<result property="cssClass" column="css_class" />
<result property="listClass" column="list_class" />
<result property="isDefault" column="is_default" />
<result property="status" column="status" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
</resultMap>
<sql id="selectDictDataVo">
select dict_code, dict_sort, dict_label, dict_value, dict_type, css_class, list_class, is_default, status, create_by, create_time, remark
from sys_dict_data
</sql>
<select id="selectDictDataList" parameterType="SysDictData" resultMap="SysDictDataResult">
<include refid="selectDictDataVo"/>
<where>
<if test="dictType != null and dictType != ''">
AND dict_type = #{dictType}
</if>
<if test="dictLabel != null and dictLabel != ''">
AND dict_label like concat('%', #{dictLabel}, '%')
</if>
<if test="status != null and status != ''">
AND status = #{status}
</if>
</where>
</select>
<select id="selectDictDataByType" parameterType="SysDictData" resultMap="SysDictDataResult">
<include refid="selectDictDataVo"/>
where status = '0' and dict_type = #{dictType} order by dict_sort asc
</select>
<select id="selectDictLabel" resultType="String">
select dict_label from sys_dict_data
where dict_type = #{dictType} and dict_value = #{dictValue}
</select>
<select id="selectDictDataById" parameterType="Long" resultMap="SysDictDataResult">
<include refid="selectDictDataVo"/>
where dict_code = #{dictCode}
</select>
<select id="countDictDataByType" resultType="Integer">
select count(1) from sys_dict_data where dict_type=#{dictType}
</select>
<delete id="deleteDictDataById" parameterType="Long">
delete from sys_dict_data where dict_code = #{dictCode}
</delete>
<delete id="deleteDictDataByIds" parameterType="String">
delete from sys_dict_data where dict_code in
<foreach collection="array" item="dictCode" open="(" separator="," close=")">
#{dictCode}
</foreach>
</delete>
<update id="updateDictData" parameterType="SysDictData">
update sys_dict_data
<set>
<if test="dictSort != null">dict_sort = #{dictSort},</if>
<if test="dictLabel != null and dictLabel != ''">dict_label = #{dictLabel},</if>
<if test="dictValue != null and dictValue != ''">dict_value = #{dictValue},</if>
<if test="dictType != null and dictType != ''">dict_type = #{dictType},</if>
<if test="cssClass != null">css_class = #{cssClass},</if>
<if test="listClass != null">list_class = #{listClass},</if>
<if test="isDefault != null and isDefault != ''">is_default = #{isDefault},</if>
<if test="status != null">status = #{status},</if>
<if test="remark != null">remark = #{remark},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
update_time = sysdate()
</set>
where dict_code = #{dictCode}
</update>
<update id="updateDictDataType" parameterType="String">
update sys_dict_data set dict_type = #{newDictType} where dict_type = #{oldDictType}
</update>
<insert id="insertDictData" parameterType="SysDictData">
insert into sys_dict_data(
<if test="dictSort != null">dict_sort,</if>
<if test="dictLabel != null and dictLabel != ''">dict_label,</if>
<if test="dictValue != null and dictValue != ''">dict_value,</if>
<if test="dictType != null and dictType != ''">dict_type,</if>
<if test="cssClass != null and cssClass != ''">css_class,</if>
<if test="listClass != null and listClass != ''">list_class,</if>
<if test="isDefault != null and isDefault != ''">is_default,</if>
<if test="status != null">status,</if>
<if test="remark != null and remark != ''">remark,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
create_time
)values(
<if test="dictSort != null">#{dictSort},</if>
<if test="dictLabel != null and dictLabel != ''">#{dictLabel},</if>
<if test="dictValue != null and dictValue != ''">#{dictValue},</if>
<if test="dictType != null and dictType != ''">#{dictType},</if>
<if test="cssClass != null and cssClass != ''">#{cssClass},</if>
<if test="listClass != null and listClass != ''">#{listClass},</if>
<if test="isDefault != null and isDefault != ''">#{isDefault},</if>
<if test="status != null">#{status},</if>
<if test="remark != null and remark != ''">#{remark},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
sysdate()
)
</insert>
</mapper>

View File

@ -1,105 +0,0 @@
<?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.ruoyi.system.mapper.SysDictTypeMapper">
<resultMap type="SysDictType" id="SysDictTypeResult">
<id property="dictId" column="dict_id" />
<result property="dictName" column="dict_name" />
<result property="dictType" column="dict_type" />
<result property="status" column="status" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
</resultMap>
<sql id="selectDictTypeVo">
select dict_id, dict_name, dict_type, status, create_by, create_time, remark
from sys_dict_type
</sql>
<select id="selectDictTypeList" parameterType="SysDictType" resultMap="SysDictTypeResult">
<include refid="selectDictTypeVo"/>
<where>
<if test="dictName != null and dictName != ''">
AND dict_name like concat('%', #{dictName}, '%')
</if>
<if test="status != null and status != ''">
AND status = #{status}
</if>
<if test="dictType != null and dictType != ''">
AND dict_type like concat('%', #{dictType}, '%')
</if>
<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
and date_format(create_time,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
</if>
<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
and date_format(create_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
</if>
</where>
</select>
<select id="selectDictTypeAll" resultMap="SysDictTypeResult">
<include refid="selectDictTypeVo"/>
</select>
<select id="selectDictTypeById" parameterType="Long" resultMap="SysDictTypeResult">
<include refid="selectDictTypeVo"/>
where dict_id = #{dictId}
</select>
<select id="selectDictTypeByType" parameterType="String" resultMap="SysDictTypeResult">
<include refid="selectDictTypeVo"/>
where dict_type = #{dictType}
</select>
<select id="checkDictTypeUnique" parameterType="String" resultMap="SysDictTypeResult">
<include refid="selectDictTypeVo"/>
where dict_type = #{dictType} limit 1
</select>
<delete id="deleteDictTypeById" parameterType="Long">
delete from sys_dict_type where dict_id = #{dictId}
</delete>
<delete id="deleteDictTypeByIds" parameterType="Long">
delete from sys_dict_type where dict_id in
<foreach collection="array" item="dictId" open="(" separator="," close=")">
#{dictId}
</foreach>
</delete>
<update id="updateDictType" parameterType="SysDictType">
update sys_dict_type
<set>
<if test="dictName != null and dictName != ''">dict_name = #{dictName},</if>
<if test="dictType != null and dictType != ''">dict_type = #{dictType},</if>
<if test="status != null">status = #{status},</if>
<if test="remark != null">remark = #{remark},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
update_time = sysdate()
</set>
where dict_id = #{dictId}
</update>
<insert id="insertDictType" parameterType="SysDictType">
insert into sys_dict_type(
<if test="dictName != null and dictName != ''">dict_name,</if>
<if test="dictType != null and dictType != ''">dict_type,</if>
<if test="status != null">status,</if>
<if test="remark != null and remark != ''">remark,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
create_time
)values(
<if test="dictName != null and dictName != ''">#{dictName},</if>
<if test="dictType != null and dictType != ''">#{dictType},</if>
<if test="status != null">#{status},</if>
<if test="remark != null and remark != ''">#{remark},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
sysdate()
)
</insert>
</mapper>

View File

@ -1,180 +0,0 @@
<?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.ruoyi.system.mapper.SysMenuMapper">
<resultMap type="SysMenu" id="SysMenuResult">
<id property="menuId" column="menu_id" />
<result property="menuName" column="menu_name" />
<result property="parentName" column="parent_name" />
<result property="parentId" column="parent_id" />
<result property="orderNum" column="order_num" />
<result property="url" column="url" />
<result property="target" column="target" />
<result property="menuType" column="menu_type" />
<result property="visible" column="visible" />
<result property="perms" column="perms" />
<result property="icon" column="icon" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateTime" column="update_time" />
<result property="updateBy" column="update_by" />
<result property="remark" column="remark" />
</resultMap>
<sql id="selectMenuVo">
select menu_id, menu_name, parent_id, order_num, url, target, menu_type, visible, ifnull(perms,'') as perms, icon, create_by, create_time
from sys_menu
</sql>
<select id="selectMenusByUserId" parameterType="Long" resultMap="SysMenuResult">
select distinct m.menu_id, m.parent_id, m.menu_name, m.url, m.visible, ifnull(m.perms,'') as perms, m.target, m.menu_type, m.icon, m.order_num, m.create_time
from sys_menu m
left join sys_role_menu rm on m.menu_id = rm.menu_id
left join sys_user_role ur on rm.role_id = ur.role_id
LEFT JOIN sys_role ro on ur.role_id = ro.role_id
where ur.user_id = #{userId} and m.menu_type in ('M', 'C') and m.visible = 0 AND ro.status = 0
order by m.parent_id, m.order_num
</select>
<select id="selectMenuNormalAll" resultMap="SysMenuResult">
select distinct m.menu_id, m.parent_id, m.menu_name, m.url, m.visible, ifnull(m.perms,'') as perms, m.target, m.menu_type, m.icon, m.order_num, m.create_time
from sys_menu m
where m.menu_type in ('M', 'C') and m.visible = 0
order by m.parent_id, m.order_num
</select>
<select id="selectMenuAll" resultMap="SysMenuResult">
<include refid="selectMenuVo"/>
order by parent_id, order_num
</select>
<select id="selectMenuAllByUserId" parameterType="Long" resultMap="SysMenuResult">
select distinct m.menu_id, m.parent_id, m.menu_name, m.url, m.visible, ifnull(m.perms,'') as perms, m.target, m.menu_type, m.icon, m.order_num, m.create_time
from sys_menu m
left join sys_role_menu rm on m.menu_id = rm.menu_id
left join sys_user_role ur on rm.role_id = ur.role_id
LEFT JOIN sys_role ro on ur.role_id = ro.role_id
where ur.user_id = #{userId}
order by m.parent_id, m.order_num
</select>
<select id="selectPermsByUserId" parameterType="Long" resultType="String">
select distinct m.perms
from sys_menu m
left join sys_role_menu rm on m.menu_id = rm.menu_id
left join sys_user_role ur on rm.role_id = ur.role_id
left join sys_role r on r.role_id = ur.role_id
where m.visible = '0' and r.status = '0' and ur.user_id = #{userId}
</select>
<select id="selectMenuTree" parameterType="Long" resultType="String">
select concat(m.menu_id, ifnull(m.perms,'')) as perms
from sys_menu m
left join sys_role_menu rm on m.menu_id = rm.menu_id
where rm.role_id = #{roleId}
order by m.parent_id, m.order_num
</select>
<select id="selectMenuList" parameterType="SysMenu" resultMap="SysMenuResult">
<include refid="selectMenuVo"/>
<where>
<if test="menuName != null and menuName != ''">
AND menu_name like concat('%', #{menuName}, '%')
</if>
<if test="visible != null and visible != ''">
AND visible = #{visible}
</if>
</where>
order by parent_id, order_num
</select>
<select id="selectMenuListByUserId" parameterType="SysMenu" resultMap="SysMenuResult">
select distinct m.menu_id, m.parent_id, m.menu_name, m.url, m.visible, ifnull(m.perms,'') as perms, m.target, m.menu_type, m.icon, m.order_num, m.create_time
from sys_menu m
left join sys_role_menu rm on m.menu_id = rm.menu_id
left join sys_user_role ur on rm.role_id = ur.role_id
LEFT JOIN sys_role ro on ur.role_id = ro.role_id
where ur.user_id = #{params.userId}
<if test="menuName != null and menuName != ''">
AND m.menu_name like concat('%', #{menuName}, '%')
</if>
<if test="visible != null and visible != ''">
AND m.visible = #{visible}
</if>
order by m.parent_id, m.order_num
</select>
<delete id="deleteMenuById" parameterType="Long">
delete from sys_menu where menu_id = #{menuId} or parent_id = #{menuId}
</delete>
<select id="selectMenuById" parameterType="Long" resultMap="SysMenuResult">
SELECT t.menu_id, t.parent_id, t.menu_name, t.order_num, t.url, t.target, t.menu_type, t.visible, t.perms, t.icon, t.remark,
(SELECT menu_name FROM sys_menu WHERE menu_id = t.parent_id) parent_name
FROM sys_menu t
where t.menu_id = #{menuId}
</select>
<select id="selectCountMenuByParentId" resultType="Integer">
select count(1) from sys_menu where parent_id=#{menuId}
</select>
<select id="checkMenuNameUnique" parameterType="SysMenu" resultMap="SysMenuResult">
<include refid="selectMenuVo"/>
where menu_name=#{menuName} and parent_id = #{parentId} limit 1
</select>
<update id="updateMenu" parameterType="SysMenu">
update sys_menu
<set>
<if test="menuName != null and menuName != ''">menu_name = #{menuName},</if>
<if test="parentId != null and parentId != 0">parent_id = #{parentId},</if>
<if test="orderNum != null and orderNum != ''">order_num = #{orderNum},</if>
<if test="url != null">url = #{url},</if>
<if test="target != null and target != ''">target = #{target},</if>
<if test="menuType != null and menuType != ''">menu_type = #{menuType},</if>
<if test="visible != null">visible = #{visible},</if>
<if test="perms !=null">perms = #{perms},</if>
<if test="icon !=null and icon != ''">icon = #{icon},</if>
<if test="remark != null">remark = #{remark},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
update_time = sysdate()
</set>
where menu_id = #{menuId}
</update>
<insert id="insertMenu" parameterType="SysMenu">
insert into sys_menu(
<if test="menuId != null and menuId != 0">menu_id,</if>
<if test="parentId != null and parentId != 0">parent_id,</if>
<if test="menuName != null and menuName != ''">menu_name,</if>
<if test="orderNum != null and orderNum != ''">order_num,</if>
<if test="url != null and url != ''">url,</if>
<if test="target != null and target != ''">target,</if>
<if test="menuType != null and menuType != ''">menu_type,</if>
<if test="visible != null">visible,</if>
<if test="perms !=null and perms != ''">perms,</if>
<if test="icon != null and icon != ''">icon,</if>
<if test="remark != null and remark != ''">remark,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
create_time
)values(
<if test="menuId != null and menuId != 0">#{menuId},</if>
<if test="parentId != null and parentId != 0">#{parentId},</if>
<if test="menuName != null and menuName != ''">#{menuName},</if>
<if test="orderNum != null and orderNum != ''">#{orderNum},</if>
<if test="url != null and url != ''">#{url},</if>
<if test="target != null and target != ''">#{target},</if>
<if test="menuType != null and menuType != ''">#{menuType},</if>
<if test="visible != null">#{visible},</if>
<if test="perms !=null and perms != ''">#{perms},</if>
<if test="icon != null and icon != ''">#{icon},</if>
<if test="remark != null and remark != ''">#{remark},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
sysdate()
)
</insert>
</mapper>

View File

@ -1,110 +0,0 @@
<?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.ruoyi.system.mapper.SysPostMapper">
<resultMap type="SysPost" id="SysPostResult">
<id property="postId" column="post_id" />
<result property="postCode" column="post_code" />
<result property="postName" column="post_name" />
<result property="postSort" column="post_sort" />
<result property="status" column="status" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="remark" column="remark" />
</resultMap>
<sql id="selectPostVo">
select post_id, post_code, post_name, post_sort, status, create_by, create_time, remark
from sys_post
</sql>
<select id="selectPostList" parameterType="SysPost" resultMap="SysPostResult">
<include refid="selectPostVo"/>
<where>
<if test="postCode != null and postCode != ''">
AND post_code like concat('%', #{postCode}, '%')
</if>
<if test="status != null and status != ''">
AND status = #{status}
</if>
<if test="postName != null and postName != ''">
AND post_name like concat('%', #{postName}, '%')
</if>
</where>
</select>
<select id="selectPostAll" resultMap="SysPostResult">
<include refid="selectPostVo"/>
</select>
<select id="selectPostsByUserId" parameterType="Long" resultMap="SysPostResult">
SELECT p.post_id, p.post_name, p.post_code
FROM sys_user u
LEFT JOIN sys_user_post up ON u.user_id = up.user_id
LEFT JOIN sys_post p ON up.post_id = p.post_id
WHERE up.user_id = #{userId}
</select>
<select id="selectPostById" parameterType="Long" resultMap="SysPostResult">
<include refid="selectPostVo"/>
where post_id = #{postId}
</select>
<select id="checkPostNameUnique" parameterType="String" resultMap="SysPostResult">
<include refid="selectPostVo"/>
where post_name=#{postName} limit 1
</select>
<select id="checkPostCodeUnique" parameterType="String" resultMap="SysPostResult">
<include refid="selectPostVo"/>
where post_code=#{postCode} limit 1
</select>
<delete id="deletePostByIds" parameterType="Long">
delete from sys_post where post_id in
<foreach collection="array" item="postId" open="(" separator="," close=")">
#{postId}
</foreach>
</delete>
<update id="updatePost" parameterType="SysPost">
update sys_post
<set>
<if test="postCode != null and postCode != ''">post_code = #{postCode},</if>
<if test="postName != null and postName != ''">post_name = #{postName},</if>
<if test="postSort != null and postSort != ''">post_sort = #{postSort},</if>
<if test="status != null and status != ''">status = #{status},</if>
<if test="remark != null">remark = #{remark},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
update_time = sysdate()
</set>
where post_id = #{postId}
</update>
<insert id="insertPost" parameterType="SysPost" useGeneratedKeys="true" keyProperty="postId">
insert into sys_post(
<if test="postId != null and postId != 0">post_id,</if>
<if test="postCode != null and postCode != ''">post_code,</if>
<if test="postName != null and postName != ''">post_name,</if>
<if test="postSort != null and postSort != ''">post_sort,</if>
<if test="status != null and status != ''">status,</if>
<if test="remark != null and remark != ''">remark,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
create_time
)values(
<if test="postId != null and postId != 0">#{postId},</if>
<if test="postCode != null and postCode != ''">#{postCode},</if>
<if test="postName != null and postName != ''">#{postName},</if>
<if test="postSort != null and postSort != ''">#{postSort},</if>
<if test="status != null and status != ''">#{status},</if>
<if test="remark != null and remark != ''">#{remark},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
sysdate()
)
</insert>
</mapper>

View File

@ -1,131 +0,0 @@
<?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.ruoyi.system.mapper.SysRoleMapper">
<resultMap type="SysRole" id="SysRoleResult">
<id property="roleId" column="role_id" />
<result property="roleName" column="role_name" />
<result property="roleKey" column="role_key" />
<result property="roleSort" column="role_sort" />
<result property="dataScope" column="data_scope" />
<result property="status" column="status" />
<result property="delFlag" column="del_flag" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="remark" column="remark" />
</resultMap>
<sql id="selectRoleContactVo">
select distinct r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope,
r.status, r.del_flag, r.create_time, r.remark
from sys_role r
left join sys_user_role ur on ur.role_id = r.role_id
left join sys_user u on u.user_id = ur.user_id
left join sys_dept d on u.dept_id = d.dept_id
</sql>
<sql id="selectRoleVo">
select r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, r.status, r.del_flag, r.create_time, r.remark
from sys_role r
</sql>
<select id="selectRoleList" parameterType="SysRole" resultMap="SysRoleResult">
<include refid="selectRoleContactVo"/>
where r.del_flag = '0'
<if test="roleName != null and roleName != ''">
AND r.role_name like concat('%', #{roleName}, '%')
</if>
<if test="status != null and status != ''">
AND r.status = #{status}
</if>
<if test="roleKey != null and roleKey != ''">
AND r.role_key like concat('%', #{roleKey}, '%')
</if>
<if test="dataScope != null and dataScope != ''">
AND r.data_scope = #{dataScope}
</if>
<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
and date_format(r.create_time,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
</if>
<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
and date_format(r.create_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
</if>
<!-- 数据范围过滤 -->
${params.dataScope}
</select>
<select id="selectRolesByUserId" parameterType="Long" resultMap="SysRoleResult">
<include refid="selectRoleContactVo"/>
WHERE r.del_flag = '0' and ur.user_id = #{userId}
</select>
<select id="selectRoleById" parameterType="Long" resultMap="SysRoleResult">
<include refid="selectRoleVo"/>
where r.del_flag = '0' and r.role_id = #{roleId}
</select>
<select id="checkRoleNameUnique" parameterType="String" resultMap="SysRoleResult">
<include refid="selectRoleVo"/>
where r.role_name=#{roleName} limit 1
</select>
<select id="checkRoleKeyUnique" parameterType="String" resultMap="SysRoleResult">
<include refid="selectRoleVo"/>
where r.role_key=#{roleKey} limit 1
</select>
<delete id="deleteRoleById" parameterType="Long">
delete from sys_role where role_id = #{roleId}
</delete>
<delete id="deleteRoleByIds" parameterType="Long">
update sys_role set del_flag = '2' where role_id in
<foreach collection="array" item="roleId" open="(" separator="," close=")">
#{roleId}
</foreach>
</delete>
<update id="updateRole" parameterType="SysRole">
update sys_role
<set>
<if test="roleName != null and roleName != ''">role_name = #{roleName},</if>
<if test="roleKey != null and roleKey != ''">role_key = #{roleKey},</if>
<if test="roleSort != null and roleSort != ''">role_sort = #{roleSort},</if>
<if test="dataScope != null and dataScope != ''">data_scope = #{dataScope},</if>
<if test="status != null and status != ''">status = #{status},</if>
<if test="remark != null">remark = #{remark},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
update_time = sysdate()
</set>
where role_id = #{roleId}
</update>
<insert id="insertRole" parameterType="SysRole" useGeneratedKeys="true" keyProperty="roleId">
insert into sys_role(
<if test="roleId != null and roleId != 0">role_id,</if>
<if test="roleName != null and roleName != ''">role_name,</if>
<if test="roleKey != null and roleKey != ''">role_key,</if>
<if test="roleSort != null and roleSort != ''">role_sort,</if>
<if test="dataScope != null and dataScope != ''">data_scope,</if>
<if test="status != null and status != ''">status,</if>
<if test="remark != null and remark != ''">remark,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
create_time
)values(
<if test="roleId != null and roleId != 0">#{roleId},</if>
<if test="roleName != null and roleName != ''">#{roleName},</if>
<if test="roleKey != null and roleKey != ''">#{roleKey},</if>
<if test="roleSort != null and roleSort != ''">#{roleSort},</if>
<if test="dataScope != null and dataScope != ''">#{dataScope},</if>
<if test="status != null and status != ''">#{status},</if>
<if test="remark != null and remark != ''">#{remark},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
sysdate()
)
</insert>
</mapper>

View File

@ -1,223 +0,0 @@
<?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.ruoyi.system.mapper.SysUserMapper">
<resultMap type="SysUser" id="SysUserResult">
<id property="userId" column="user_id" />
<result property="deptId" column="dept_id" />
<result property="loginName" column="login_name" />
<result property="userName" column="user_name" />
<result property="userType" column="user_type" />
<result property="email" column="email" />
<result property="phonenumber" column="phonenumber" />
<result property="sex" column="sex" />
<result property="avatar" column="avatar" />
<result property="password" column="password" />
<result property="salt" column="salt" />
<result property="status" column="status" />
<result property="delFlag" column="del_flag" />
<result property="loginIp" column="login_ip" />
<result property="loginDate" column="login_date" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="remark" column="remark" />
<association property="dept" column="dept_id" javaType="SysDept" resultMap="deptResult" />
<collection property="roles" javaType="java.util.List" resultMap="RoleResult" />
</resultMap>
<resultMap id="deptResult" type="SysDept">
<id property="deptId" column="dept_id" />
<result property="parentId" column="parent_id" />
<result property="deptName" column="dept_name" />
<result property="orderNum" column="order_num" />
<result property="leader" column="leader" />
<result property="status" column="dept_status" />
</resultMap>
<resultMap id="RoleResult" type="SysRole">
<id property="roleId" column="role_id" />
<result property="roleName" column="role_name" />
<result property="roleKey" column="role_key" />
<result property="roleSort" column="role_sort" />
<result property="dataScope" column="data_scope" />
<result property="status" column="role_status" />
</resultMap>
<sql id="selectUserVo">
select u.user_id, u.dept_id, u.login_name, u.user_name, u.user_type, u.email, u.avatar, u.phonenumber, u.sex, u.password, u.salt, u.status, u.del_flag, u.login_ip, u.login_date, u.create_time, u.remark,
d.dept_id, d.parent_id, d.dept_name, d.order_num, d.leader, d.status as dept_status,
r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, r.status as role_status
from sys_user u
left join sys_dept d on u.dept_id = d.dept_id
left join sys_user_role ur on u.user_id = ur.user_id
left join sys_role r on r.role_id = ur.role_id
</sql>
<select id="selectUserList" parameterType="SysUser" resultMap="SysUserResult">
select u.user_id, u.dept_id, u.login_name, u.user_name, u.user_type, u.email, u.avatar, u.phonenumber, u.password, u.sex, u.salt, u.status, u.del_flag, u.login_ip, u.login_date, u.create_by, u.create_time, u.remark, d.dept_name, d.leader from sys_user u
left join sys_dept d on u.dept_id = d.dept_id
where u.del_flag = '0'
<if test="loginName != null and loginName != ''">
AND u.login_name like concat('%', #{loginName}, '%')
</if>
<if test="status != null and status != ''">
AND u.status = #{status}
</if>
<if test="phonenumber != null and phonenumber != ''">
AND u.phonenumber like concat('%', #{phonenumber}, '%')
</if>
<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
AND date_format(u.create_time,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
</if>
<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
AND date_format(u.create_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
</if>
<if test="deptId != null and deptId != 0">
AND (u.dept_id = #{deptId} OR u.dept_id IN ( SELECT t.dept_id FROM sys_dept t WHERE FIND_IN_SET (#{deptId},ancestors) ))
</if>
<!-- 数据范围过滤 -->
${params.dataScope}
</select>
<select id="selectAllocatedList" parameterType="SysUser" resultMap="SysUserResult">
select distinct u.user_id, u.dept_id, u.login_name, u.user_name, u.user_type, u.email, u.avatar, u.phonenumber, u.status, u.create_time
from sys_user u
left join sys_dept d on u.dept_id = d.dept_id
left join sys_user_role ur on u.user_id = ur.user_id
left join sys_role r on r.role_id = ur.role_id
where u.del_flag = '0' and r.role_id = #{roleId}
<if test="loginName != null and loginName != ''">
AND u.login_name like concat('%', #{loginName}, '%')
</if>
<if test="phonenumber != null and phonenumber != ''">
AND u.phonenumber like concat('%', #{phonenumber}, '%')
</if>
<!-- 数据范围过滤 -->
${params.dataScope}
</select>
<select id="selectUnallocatedList" parameterType="SysUser" resultMap="SysUserResult">
select distinct u.user_id, u.dept_id, u.login_name, u.user_name, u.user_type, u.email, u.avatar, u.phonenumber, u.status, u.create_time
from sys_user u
left join sys_dept d on u.dept_id = d.dept_id
left join sys_user_role ur on u.user_id = ur.user_id
left join sys_role r on r.role_id = ur.role_id
where u.del_flag = '0' and (r.role_id != #{roleId} or r.role_id IS NULL)
and u.user_id not in (select u.user_id from sys_user u inner join sys_user_role ur on u.user_id = ur.user_id and ur.role_id = #{roleId})
<if test="loginName != null and loginName != ''">
AND u.login_name like concat('%', #{loginName}, '%')
</if>
<if test="phonenumber != null and phonenumber != ''">
AND u.phonenumber like concat('%', #{phonenumber}, '%')
</if>
<!-- 数据范围过滤 -->
${params.dataScope}
</select>
<select id="selectUserByLoginName" parameterType="String" resultMap="SysUserResult">
<include refid="selectUserVo"/>
where u.login_name = #{userName}
</select>
<select id="selectUserByPhoneNumber" parameterType="String" resultMap="SysUserResult">
<include refid="selectUserVo"/>
where u.phonenumber = #{phonenumber}
</select>
<select id="selectUserByEmail" parameterType="String" resultMap="SysUserResult">
<include refid="selectUserVo"/>
where u.email = #{email}
</select>
<select id="checkLoginNameUnique" parameterType="String" resultType="int">
select count(1) from sys_user where login_name=#{loginName} limit 1
</select>
<select id="checkPhoneUnique" parameterType="String" resultMap="SysUserResult">
select user_id, phonenumber from sys_user where phonenumber=#{phonenumber} limit 1
</select>
<select id="checkEmailUnique" parameterType="String" resultMap="SysUserResult">
select user_id, email from sys_user where email=#{email} limit 1
</select>
<select id="selectUserById" parameterType="Long" resultMap="SysUserResult">
<include refid="selectUserVo"/>
where u.user_id = #{userId}
</select>
<delete id="deleteUserById" parameterType="Long">
update sys_user set del_flag = '2' where user_id = #{userId}
</delete>
<delete id="deleteUserByIds" parameterType="Long">
update sys_user set del_flag = '2' where user_id in
<foreach collection="array" item="userId" open="(" separator="," close=")">
#{userId}
</foreach>
</delete>
<update id="updateUser" parameterType="SysUser">
update sys_user
<set>
<if test="deptId != null and deptId != 0">dept_id = #{deptId},</if>
<if test="loginName != null and loginName != ''">login_name = #{loginName},</if>
<if test="userName != null and userName != ''">user_name = #{userName},</if>
<if test="userType != null and userType != ''">user_type = #{userType},</if>
<if test="email != null and email != ''">email = #{email},</if>
<if test="phonenumber != null and phonenumber != ''">phonenumber = #{phonenumber},</if>
<if test="sex != null and sex != ''">sex = #{sex},</if>
<if test="avatar != null and avatar != ''">avatar = #{avatar},</if>
<if test="password != null and password != ''">password = #{password},</if>
<if test="salt != null and salt != ''">salt = #{salt},</if>
<if test="status != null and status != ''">status = #{status},</if>
<if test="loginIp != null and loginIp != ''">login_ip = #{loginIp},</if>
<if test="loginDate != null">login_date = #{loginDate},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
<if test="remark != null">remark = #{remark},</if>
update_time = sysdate()
</set>
where user_id = #{userId}
</update>
<insert id="insertUser" parameterType="SysUser" useGeneratedKeys="true" keyProperty="userId">
insert into sys_user(
<if test="userId != null and userId != 0">user_id,</if>
<if test="deptId != null and deptId != 0">dept_id,</if>
<if test="loginName != null and loginName != ''">login_name,</if>
<if test="userName != null and userName != ''">user_name,</if>
<if test="userType != null and userType != ''">user_type,</if>
<if test="email != null and email != ''">email,</if>
<if test="avatar != null and avatar != ''">avatar,</if>
<if test="phonenumber != null and phonenumber != ''">phonenumber,</if>
<if test="sex != null and sex != ''">sex,</if>
<if test="password != null and password != ''">password,</if>
<if test="salt != null and salt != ''">salt,</if>
<if test="status != null and status != ''">status,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
<if test="remark != null and remark != ''">remark,</if>
create_time
)values(
<if test="userId != null and userId != ''">#{userId},</if>
<if test="deptId != null and deptId != ''">#{deptId},</if>
<if test="loginName != null and loginName != ''">#{loginName},</if>
<if test="userName != null and userName != ''">#{userName},</if>
<if test="userType != null and userType != ''">#{userType},</if>
<if test="email != null and email != ''">#{email},</if>
<if test="avatar != null and avatar != ''">#{avatar},</if>
<if test="phonenumber != null and phonenumber != ''">#{phonenumber},</if>
<if test="sex != null and sex != ''">#{sex},</if>
<if test="password != null and password != ''">#{password},</if>
<if test="salt != null and salt != ''">#{salt},</if>
<if test="status != null and status != ''">#{status},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
<if test="remark != null and remark != ''">#{remark},</if>
sysdate()
)
</insert>
</mapper>

View File

@ -1,48 +0,0 @@
<?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.ruoyi.system.mapper.SysUserRoleMapper">
<resultMap type="SysUserRole" id="SysUserRoleResult">
<result property="userId" column="user_id" />
<result property="roleId" column="role_id" />
</resultMap>
<select id="selectUserRoleByUserId" parameterType="Long" resultMap="SysUserRoleResult">
select user_id, role_id from sys_user_role where user_id = #{userId}
</select>
<delete id="deleteUserRoleByUserId" parameterType="Long">
delete from sys_user_role where user_id = #{userId}
</delete>
<select id="countUserRoleByRoleId" resultType="Integer">
select count(1) from sys_user_role where role_id = #{roleId}
</select>
<delete id="deleteUserRole" parameterType="Long">
delete from sys_user_role where user_id in
<foreach collection="array" item="userId" open="(" separator="," close=")">
#{userId}
</foreach>
</delete>
<insert id="batchUserRole">
insert into sys_user_role(user_id, role_id) values
<foreach item="item" index="index" collection="list" separator=",">
(#{item.userId},#{item.roleId})
</foreach>
</insert>
<delete id="deleteUserRoleInfo" parameterType="SysUserRole">
delete from sys_user_role where user_id=#{userId} and role_id=#{roleId}
</delete>
<delete id="deleteUserRoleInfos">
delete from sys_user_role where role_id=#{roleId} and user_id in
<foreach collection="userIds" item="userId" open="(" separator="," close=")">
#{userId}
</foreach>
</delete>
</mapper>