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("存儲數據庫成功!");
}
}