https://daily.zhihu.com/story/9725845
package com.tansuo365.test1.controller.othercontrol;
import com.tansuo365.test1.bean.otherbean.Project;
import com.tansuo365.test1.service.otherservice.DProjectService;
import com.tansuo365.test1.service.otherservice.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/admin/project")
public class ProjectController {
@Autowired
private ProjectService projectService;
@Autowired
private DProjectService dProjectService;
@PostMapping("/loadProjectTree")
public String loadProjectTree(){
return getAllByParentId(-1).toString();
}
@RequestMapping("/save")
public Map<String,Object> save(Project project){
Map<String, Object> resultMap = new HashMap<>();
if(project.getP_id()==-1 || null==project.getP_id()){ //一级菜单
project.setIcon("icon-folderOpen");
project.setState(1);
}else { //二级菜单
project.setIcon("icon-folder");
project.setState(2);
}
projectService.insertSelective(project);
//
resultMap.put("success", true);
return resultMap;
}
@RequestMapping("/delete")
public Map<String,Object> delete(int id){
Map<String, Object> resultMap = new HashMap<>();
Project project=projectService.selectByPrimaryKey(id); //获取要删除的数据
//查看该项目是否是一级,一级下面是否有二级
List<Project> secondProjectList = projectService.findByParentId(project.getId());
int secondSize = secondProjectList.size();
System.out.println("secondSize:"+secondSize);
if(secondSize>0){ // 如果有对应二级项目,则同时一并删除
Integer[] ids = new Integer[secondSize];
for(int i=0; i<secondSize;i++){
Integer everyId = secondProjectList.get(i).getId();
ids[i]=everyId;
}
projectService.deleteBatchByPKArr(ids); //批量删除二级项目分类
dProjectService.deleteBatchByWidArr(ids);//批量删除二级项目列表
projectService.deleteByPrimaryKey(id);//删除一级项目分类
dProjectService.deleteByWid(id);//删除一级项目分类对应的列表
}else{
//假设其size不大于0,则只删除一级菜单和其对应项目列表
projectService.deleteByPrimaryKey(id); // 删除
dProjectService.deleteByWid(id);
}
resultMap.put("success", true);
return resultMap;
}
/**
* 根据父节点递归获取所有商品类别信息
* 渲染树形第一步
* @param parentId
* @return
*/
public JsonArray getAllByParentId(Integer parentId){
JsonArray jsonArray=this.getByParentId(parentId);
for(int i=0;i<jsonArray.size();i++){
JsonObject jsonObject=(JsonObject) jsonArray.get(i);
//如果是二级菜单,则不再继续添加子项
if("second".equals(jsonObject.get("state").getAsString())){
continue;
//如果是一级菜单,则查找一级下面是否有二级菜单
}else if("first".equals(jsonObject.get("state").getAsString())){
System.out.println("建立了children子集,数据ID:"+jsonObject.get("id"));
jsonObject.add("children", getAllByParentId(jsonObject.get("id").getAsInt()));
}else{
}
}
return jsonArray;
}
/**
* 根据父节点查询子节点
* @param p_id
* @return
*/
private JsonArray getByParentId(Integer p_id){
JsonArray jsonArray=new JsonArray();
//获取了第一组 [一级] 树形菜单
List<Project> projectList=projectService.findByParentId(p_id);
for(Project project:projectList){
//回传的jsonArray的item
JsonObject jsonObject=new JsonObject();
jsonObject.addProperty("id", project.getId()); // 节点id
jsonObject.addProperty("text", project.getXiangmumingcheng()); // 节点名称
if(project.getState()==1){
jsonObject.addProperty("state", "first"); // 根节点 一级
}else if(project.getState()==2){
jsonObject.addProperty("state", "second"); // 叶子节点 二级
}else{
}
jsonObject.addProperty("iconCls", project.getIcon());
JsonObject attributeObject=new JsonObject(); // 扩展属性
attributeObject.addProperty("state",project.getState()); // 节点状态 [一级/二级]
jsonObject.add("attributes", attributeObject);
jsonArray.add(jsonObject);
}
return jsonArray;
}
}
package com.tansuo365.test1.controller.othercontrol;
import com.github.pagehelper.util.StringUtil;
import com.tansuo365.test1.bean.otherbean.Menu;
import com.tansuo365.test1.bean.otherbean.Role;
import com.tansuo365.test1.bean.otherbean.RoleMenu;
import com.tansuo365.test1.mapper.othermapper.UserMapper;
import com.tansuo365.test1.service.otherservice.*;
import com.tansuo365.test1.util.MenuUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*管理员角色控制层*/
@Api(value = "管理员角色控制层", tags = "管理员角色接口 AdminRoleController", description = "管理员角色控制层,配置系统角色")
@RestController
@RequestMapping("/admin/role")
public class RoleController {
@Autowired
private UserService userService;
@Resource
private UserMapper userMapper;
@Autowired
private RoleService roleService;
@Autowired
private UserRoleService userRoleService;
@Autowired
private MenuService eMenuService;
@Autowired
private RoleMenuService roleMenuService;
// @Autowired
// private LogUtils logUtils;
@Autowired
private MenuUtils menuUtils;
// final private String ADMIN_ROLE = "admin_role";
/**
* 查询所有角色 静态
*
* @return
* @throws Exception
*/
@ApiOperation(value = "查询所有系统角色", notes = "查询所有系统角色listAllRoles")
@PostMapping("/listAllRoles")
// @RequiresPermissions(value = {"系统角色管理"})
public Map<String, Object> listAll(HttpSession session) throws Exception {
Map<String, Object> resultMap = new HashMap<>();
List<Role> list = roleService.list();
// logUtils.doLog(list, 0, LogEnum.SEARCH_ACTION, ADMIN_ROLE, session);
resultMap.put("rows", list);
return resultMap;
}
//对管理员role的动态查询
@ApiOperation(value = "动态查询所有系统角色", notes = "动态查询所有系统角色listAllRoleSelective")
@PostMapping("/listAllRoleSelective")
// @RequiresPermissions(value = {"系统角色管理"})
public Map<String, Object> listAllRoleSelective(HttpSession session, Role role) throws Exception {
Map<String, Object> resultMap = new HashMap<>();
List<Role> roles = roleService.listSelective(role);
// logUtils.doLog(roles, 0, LogEnum.SEARCH_ACTION, ADMIN_ROLE, session);
resultMap.put("rows", roles);
return resultMap;
}
//对role的新增或更改
@ApiOperation(value = "新增或更改角色信息", notes = "新增或更改角色信息")
@PostMapping("/saveRole")
// @RequiresPermissions(value = {"系统角色管理"})
public Map<String, Object> saveRole(HttpSession session, Role role) {
Map<String, Object> resultMap = new HashMap<>();
if (role.getId() == null) { //如果role的id为null,再判定role名称是否重复
try {
String roleName = role.getRolename();
System.err.println("roleName:" + roleName);
if (roleService.getByName(roleName) != null) { //每次都报错,因为如果名字不重复,肯定getByName会是null
resultMap.put("success", false);
resultMap.put("errorInfo", "角色名已经存在!");
return resultMap;
}
} catch (Exception e) {
e.printStackTrace();
}
}
int updateCode = 0;
int insertCode = 0;
if (role.getId() != null) { //不为空,则要进行升级管理员user信息
updateCode = roleService.update(role);
} else { //为空,则说明是要注册新的管理员user
insertCode = roleService.addSelective(role);
}
/*如果更新code或者插入code成功状态则success true,否则不是*/
if (updateCode == 1) {
resultMap.put("saveMessage", "管理员角色更新成功!");
resultMap.put("success", true);
// logUtils.doLog(null, updateCode, LogEnum.UPDATE_ACTION, ADMIN_ROLE, session);
}
if (insertCode == 1) {
resultMap.put("saveMessage", "管理员角色添加成功!");
resultMap.put("success", true);
// logUtils.doLog(null, updateCode, LogEnum.ADD_ACTION, ADMIN_ROLE, session);
}
if (updateCode == 1 || insertCode == 1) {
return resultMap;
} else {
resultMap.put("success", false);
resultMap.put("errorInfo", "保存失败!");
return resultMap;
}
}
/**
* @param id
* @return
* @throws Exception
*/
@ApiOperation(value = "删除角色", notes = "删除角色根据ID")
@PostMapping("/deleteRoleById")
// @RequiresPermissions(value = {"系统角色管理"})
public Map<String, Object> deleteRoleById(HttpSession session, Integer id) throws Exception {
Map<String, Object> resultMap = new HashMap<>();
userRoleService.deleteByRole(id); // 删除用户角色关联信息
int deleteCode = roleService.delete(id);
if (deleteCode == 1) {
resultMap.put("success", true);
// logUtils.doLog(null, deleteCode, LogEnum.DELETE_ACTION, ADMIN_ROLE, session);
} else {
resultMap.put("success", false);
resultMap.put("errorInfo", "删除失败了");
}
return resultMap;
}
// /**
// * 根据父节点获取所有复选框权限菜单树 Array
// * @param parentId
// * @param roleIds
// * @return
// * @throws Exception
// */
// @RequestMapping("/loadCheckMenuInfoArray")
// public String loadCheckMenuInfoArray(Integer parentId,Integer[] roleIds)throws Exception{
// //根据角色查询所有权限菜单id信息(已在impl去重),首先要获取用户的roleid(集合)
// List<Integer> menuIdList = eMenuService.findMenuIdListByRoleIds(roleIds);
// return getAllCheckedEMenuByParentId(parentId,menuIdList).toString();
// }
/**
* 根据父节点获取所有复选框权限菜单树
*
* @param parentId
* @param
* @return
* @throws Exception
*/
@ApiOperation(value = "权限菜单", notes = "根据父节点获取所有复选框权限菜单树")
@PostMapping("/loadCheckMenuInfo")
// @RequiresPermissions(value = {"系统角色管理"})
public String loadCheckMenuInfo(int parentId, int roleId) throws Exception {
List<Menu> eMenuList = eMenuService.findMenuListByRoleId(roleId);
List<Integer> eMenuIdList = new ArrayList<>();
for (Menu menu : eMenuList) {
Integer id = menu.getId();
eMenuIdList.add(id);
}
String allCheckedEMenu = menuUtils.getAllCheckedEMenuByParentId(parentId, eMenuIdList).toString();
return allCheckedEMenu;
}
/**
* 保存角色权限设置
* 该方法先根据该角色将所有对应的role_menu元组删除,
* 之后再根据树形表单中点选的menuId集合进行设置.
* saveMenuSet使用率远比刷新首页低,所以缓存放在这里,而首页获取allMenu时就简洁了
*
* @param menuIds
* @param roleId
* @return
*/
@ApiOperation(value = "保存角色权限设置", notes = "保存角色权限设置根据给定菜单ids,角色id")
// @CachePut(value = "menuIds", key = "''+#+',roleId'+#roleId", condition = "#menuIds != '' ") //即保证方法被调用,又加入缓存
// @CachePut(value = "roleMenuStr", key = "#session.getAttribute('currentUser').toString()+#session.getAttribute('roleList').toString()", condition = "#parentId != '' ")
// @CachePut(value = "roleMenuStr", key = "#menuIds+#roleId", condition = "#parentId != '' ")
@PostMapping("/saveMenuSet")
// @RequiresPermissions(value = {"系统角色管理"})
public Map<String, Object> saveMenuSet(HttpSession session, String menuIds, int roleId) {
System.out.println("inSaveMenuSet,menuIds:" + menuIds);
String message = "";
Map<String, Object> resultMap = new HashMap<>();
//根据roleid,删除role_menu元组
int deleteCode = roleMenuService.deleteByRoleId(roleId);
if (deleteCode == 1) {
//根据roleId删除roleMenu数据ok
// message = "剔除角色权限成功/";
System.out.println("删除了roleId为" + roleId + "的role_menu数据.");
}
int insertCode = 0;
int count = 0;
ArrayList menuIdList = new ArrayList();
//开始更新rolemenu
if (StringUtil.isNotEmpty(menuIds)) {
String idsStr[] = menuIds.split(",");
for (int i = 0; i < idsStr.length; i++) {
RoleMenu roleMenu = new RoleMenu();
menuIdList.add(Integer.parseInt(idsStr[i]));
//设置传入的roleid到role_menu表
roleMenu.setRid(roleId);
roleMenu.setMid(Integer.parseInt(idsStr[i]));
int code = roleMenuService.saveRoleMenu(roleMenu);
insertCode += code;
count++;
}
}
if (insertCode == count && insertCode != 0) {
resultMap.put("success", true);
message = "保存角色权限成功!";
resultMap.put("message", message);
String roleMenuStr = menuUtils.getAllCheckedEMenuByParentId(-1, menuIdList).toString();
// logUtils.doLog(null, insertCode, LogEnum.ADD_ACTION, ADMIN_ROLE, session);
return resultMap;
} else {
resultMap.put("success", false);
resultMap.put("message", "保存角色权限设置失败.");
return resultMap;
}
}
}
package com.tansuo365.test1.controller.othercontrol;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.tansuo365.test1.bean.otherbean.WuliaoTree;
import com.tansuo365.test1.service.otherservice.DWuliaoService;
import com.tansuo365.test1.service.otherservice.WuliaoTreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/admin/wuliaoTree")
public class WuliaoTreeController {
@Autowired
private WuliaoTreeService wuliaoTreeService;
@Autowired
private DWuliaoService dWuliaoService;
@PostMapping("/loadWuliaoTree")
public String loadWuliaoTree(){
return getAllByParentId(-1).toString();
}
/**
* 新模式: 获取导入后的物料表的大类, group by 同时distinct 选回 大类 集合
* 根据大类集合,创建多个物料tree的一级分类,同时点击物料tree选择时,按物料tree名称->展示不同大类list
*
* @param wuliaoTree
* @return
*/
@RequestMapping("/save")
public Map<String,Object> save(WuliaoTree wuliaoTree){
Map<String, Object> resultMap = new HashMap<>();
if(wuliaoTree.getP_id()==-1){ //一级菜单
wuliaoTree.setIcon("icon-folderOpen");
wuliaoTree.setState(1);
}else { //二级菜单
wuliaoTree.setIcon("icon-folder");
wuliaoTree.setState(2);
}
wuliaoTreeService.insertSelective(wuliaoTree);
//
resultMap.put("success", true);
return resultMap;
}
@RequestMapping("/delete")
public Map<String,Object> delete(int id){
Map<String, Object> resultMap = new HashMap<>();
WuliaoTree wuliaoTree=wuliaoTreeService.selectByPrimaryKey(id); //获取要删除的数据
//查看该项目是否是一级,一级下面是否有二级
List<WuliaoTree> secondWuliaoTreeList = wuliaoTreeService.findByParentId(wuliaoTree.getId());
int secondSize = secondWuliaoTreeList.size();
System.out.println("secondSize:"+secondSize);
if(secondSize>0){ // 如果有对应二级项目,则同时一并删除
Integer[] ids = new Integer[secondSize];
for(int i=0; i<secondSize;i++){
Integer everyOId = secondWuliaoTreeList.get(i).getId();
ids[i]=everyOId;
}
wuliaoTreeService.deleteBatchByPKArr(ids); //批量删除二级项目分类
dWuliaoService.deleteBatchByOidArr(ids);//批量删除一级下面的所有详细列表数据
wuliaoTreeService.deleteByPrimaryKey(id);//删除一级项目分类
}else{
//假设其size不大于0,则只删除一级菜单和其对应项目列表
wuliaoTreeService.deleteByPrimaryKey(id); // 删除
dWuliaoService.deleteByOid(id);
}
resultMap.put("success", true);
return resultMap;
}
/**
* 根据父节点递归获取所有商品类别信息
* 渲染树形第一步
* @param parentId
* @return
*/
public JsonArray getAllByParentId(Integer parentId){
JsonArray jsonArray=this.getByParentId(parentId);
for(int i=0;i<jsonArray.size();i++){
JsonObject jsonObject=(JsonObject) jsonArray.get(i);
//如果是二级菜单,则不再继续添加子项
if("second".equals(jsonObject.get("state").getAsString())){
continue;
//如果是一级菜单,则查找一级下面是否有二级菜单
}else if("first".equals(jsonObject.get("state").getAsString())){
System.out.println("建立了children子集,数据ID:"+jsonObject.get("id"));
jsonObject.add("children", getAllByParentId(jsonObject.get("id").getAsInt()));
}else{
}
}
return jsonArray;
}
/**
* 根据父节点查询子节点
* @param p_id
* @return
*/
private JsonArray getByParentId(Integer p_id){
JsonArray jsonArray=new JsonArray();
//获取了第一组 [一级] 树形菜单
List<WuliaoTree> wuliaoTreeList=wuliaoTreeService.findByParentId(p_id);
for(WuliaoTree wuliaoTree:wuliaoTreeList){
//回传的jsonArray的item
JsonObject jsonObject=new JsonObject();
jsonObject.addProperty("id", wuliaoTree.getId()); // 节点id
jsonObject.addProperty("text", wuliaoTree.getWuliaofenlei()); // 节点名称
if(wuliaoTree.getState()==1){
jsonObject.addProperty("state", "first"); // 根节点 一级
}else if(wuliaoTree.getState()==2){
jsonObject.addProperty("state", "second"); // 叶子节点 二级
}else{
}
jsonObject.addProperty("iconCls", wuliaoTree.getIcon());
JsonObject attributeObject=new JsonObject(); // 扩展属性
attributeObject.addProperty("state",wuliaoTree.getState()); // 节点状态 [一级/二级]
jsonObject.add("attributes", attributeObject);
jsonArray.add(jsonObject);
}
return jsonArray;
}
}
package com.tansuo365.test1.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.tansuo365.test1.bean.InfoData;
import com.tansuo365.test1.bean.otherbean.DProject;
import com.tansuo365.test1.service.excelservice.IAllDatasService;
import com.tansuo365.test1.util.BeanMapUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//listener不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
//@PropertySource(value = "classpath:excel.properties")
public class UploadProjectDataListener extends AnalysisEventListener<InfoData> {
private static final Logger LOGGER =
LoggerFactory.getLogger(UploadProjectDataListener.class);
//每隔2500条存储数据库,实际使用3000条可以,然后清理list,方便内存回收
// @Value("${onetime.batch.count}")
private int BATCH_COUNT = 3000;
List<InfoData> list = new ArrayList<InfoData>();
Map<String,Object> paramsMap;
//传入的service层,不同的货品类型调用不同的service
private IAllDatasService datasService;
private Map<String,Object> insertMap = new HashMap<>();
/**
* 通用的goodsService,代表着有关于货品价格,货品存储,货品进出口的相关增删改查等服务层
* 在本类中使用insertBatch方法,做为读取excel的分段导入时的数据保存
*
* @param datasService
*/
public UploadProjectDataListener(IAllDatasService datasService, Map<String,Object> paramsMap) {
this.datasService = datasService;
this.paramsMap = paramsMap;
}
//每一条数据解析都会来调用 TODO 如果感觉判定阻碍了传入的效率则取消 if saveCode判定
@Override
public void invoke(InfoData infoData, AnalysisContext analysisContext) {
LOGGER.info("解析到一条项目数据:{}", JSON.toJSONString(infoData));
Map map = null;
try {
map = BeanMapUtil.convertBean2Map(infoData);
} catch (Exception e) {
e.printStackTrace();
}
//这里有的参数仅适合物料表
LOGGER.info("解析到一条数据map:{}", JSON.toJSONString(map));
map.put("w_id",Integer.valueOf((String) paramsMap.get("wRoot")));
map.put("o_id",Integer.valueOf((String) paramsMap.get("oSub")));
InfoData infoDataAndWOID = null;
try {
infoDataAndWOID = BeanMapUtil.convertMapToBean(DProject.class,map);
} catch (Exception e) {
e.printStackTrace();
}
LOGGER.info("加入参数后:{}", JSON.toJSONString(infoDataAndWOID));
list.add(infoDataAndWOID);
// insertMap.put("list",list);
// List list = (List) insertMap.get("list");
// System.out.println("list.size():"+list.size());
// insertMap.put("w_id",paramsMap.get("wRoot"));
// insertMap.put("o_id",paramsMap.get("oSub")););
// insertMap.put("paramsMap",paramsMap);
//达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存.容易OOM
if (list.size() >= BATCH_COUNT) {
saveData();
list.clear();//存储完成后清理list
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
//这里也要保存数据,确保最后遗留的数据也存储到数据库
saveData();
LOGGER.info("所有数据解析保存完成!");
}
//save data , when excel data in here
private void saveData() {
LOGGER.info("{}条数据,开始存储数据库!", list.size());
datasService.insertBatch(list); //map参数
LOGGER.info("存储数据库成功!");
}
}