近期项目easyui树形集成mybatis plus表格实例
控制层
package cn.et.wk.manage.shopping.wed;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.et.wk.common.entity.Result;
import cn.et.wk.common.entity.UserInfo;
import cn.et.wk.manager.shopping.entity.Classify;
import cn.et.wk.manager.shopping.service.ClassifyService;
@Controller
@RequestMapping("/shopping/classify")
public class ClassifyController {
@Autowired
private ClassifyService classifyService;
@RequestMapping("/index")
public String index() {
return "/message/category.html";
}
@ResponseBody
@GetMapping("/query")
public Result topCategory() {
return classifyService.queryAll();
}
@ResponseBody
@GetMapping("/queryId/{id}")
public List<Classify> queryById(@PathVariable String id) {
Result queryById = classifyService.queryById(id);
return queryById.getRows();
}
// 查询所有一级分类的数据
@ResponseBody
@PostMapping("/queryTopClass")
public List<Classify> queryTopClass() {
Result queryTop = classifyService.queryTop();
return queryTop.getRows();
}
// 查询所有父类编号是parentId的数据
@ResponseBody
@PostMapping("/queryTwoClass/{parentId}")
public List<Classify> queryTwoClass(@PathVariable String parentId) {
Result queryTwo = classifyService.queryTwo(parentId);
return queryTwo.getRows();
}
//单个删除
@ResponseBody
@DeleteMapping("/delete/{parentId}")
public Result delete(@PathVariable String parentId , @RequestBody List<String> ids) {
ids.add(parentId);
Result result = classifyService.delete(ids);
return result;
}
// 多个删除
@ResponseBody
@DeleteMapping("/deleteAll")
public Result deleteAll(@RequestBody List<String> ids) {
Result delete = classifyService.delete(ids);
return delete;
}
//新增
@ResponseBody
@PostMapping("/save")
public Result save(Classify classify) {
// 获取用户id
UserInfo user = (UserInfo) SecurityUtils.getSubject().getSession().getAttribute("userInfo");
// 获取当前时间
Date now=new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String tablename=dateFormat.format(now);
// 将时间和id赋值给classify对象
classify.setCreateBy(user.getUserId());
classify.setCreateTime(tablename);
classify.setLastUpdateBy(user.getUserId());
classify.setLastUpdateTime(tablename);
Result save = classifyService.save(classify);
return save;
}
//修改
@ResponseBody
@PutMapping("/update")
public Result update(Classify classify,Integer classifyNames) {
UserInfo user = (UserInfo) SecurityUtils.getSubject().getSession().getAttribute("userInfo");
// 获取当前时间
Date now=new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String tablename=dateFormat.format(now);
// 将时间和id赋值给classify对象
classify.setCreateBy(user.getUserId());
classify.setCreateTime(tablename);
classify.setLastUpdateBy(user.getUserId());
classify.setLastUpdateTime(tablename);
Result update = classifyService.update(classify,classifyNames);
return update;
}
}
实体类(由于是树形表格在这里使用了两个实体类对象)
package cn.et.wk.manager.shopping.entity;
import java.sql.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@TableName("td_commodity_category")
public class Classify {
//商品类别编号
@TableId(type=IdType.AUTO)
//@TableField("commodity_category_no")
private int commodityCategoryNo;
//商品类别名称
@TableField("commodity_category_name")
private String classifyName;
//商品类别父编号
@TableField("commodity_category_sire")
private int classifySire=0;
//商品类别排序
@TableField("commodity_category_sort")
private int classifySort;
@TableField("commodity_category_user")
private int createBy; //创建人
@TableField("commodity_category_time")
private String createTime;//创建时间
@TableField("last_modification_user")
private int lastUpdateBy;//修改人
@TableField("last_modification_time")
private String lastUpdateTime;//修改时间
}
package cn.et.wk.manager.shopping.entity;
import lombok.Data;
@Data
public class TreeClassify {
private int id;//主键
private String region;//查找的范围
private int _parentId;//前台默认需要的字段
private int pid;//排序配合前台字段使用
}
Service接口
package cn.et.wk.manager.shopping.service;
import java.sql.SQLException;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.alibaba.fastjson.JSONObject;
import cn.et.wk.common.entity.Result;
import cn.et.wk.manager.shopping.entity.Classify;
public interface ClassifyService {
public Result queryAll();
public Result queryById(String id);
public Result queryTop();
public Result queryTwo(String parentId);
public Result delete(List<String> ids);
public Result save(Classify classify);
public Result update(Classify classify,Integer classifyNames);
}
实现
package cn.et.wk.manager.shopping.service.impl;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import cn.et.wk.common.entity.Result;
import cn.et.wk.common.service.impl.CommonServiceImpl;
import cn.et.wk.manager.shopping.entity.Classify;
import cn.et.wk.manager.shopping.entity.TreeClassify;
import cn.et.wk.manager.shopping.mapper.ClassMapper;
import cn.et.wk.manager.shopping.service.ClassifyService;
@Service
public class ClassifyServiceImpl<T,V> implements ClassifyService {
private static final Exception Exception = null;
@Autowired
private ClassMapper mapping;
@Override
public Result queryAll() {
List<Classify> selectList = mapping.selectList(null);
Result result = new Result();
List<TreeClassify> list = new ArrayList<TreeClassify>();
Iterator<Classify> iterator = selectList.iterator();
while (iterator.hasNext()) {
Classify next = iterator.next();
TreeClassify treeClassify = new TreeClassify();
treeClassify.setId(next.getCommodityCategoryNo());
treeClassify.setRegion(next.getClassifyName());
treeClassify.setPid(next.getClassifySort());
treeClassify.set_parentId(next.getClassifySire());
list.add(treeClassify);
}
result.setRows(list);
result.setTotal(list.size());
return result;
}
@Override
public Result queryById(String id) {
Classify selectById = mapping.selectById(id);
System.out.println(selectById);
List<Classify> list = new ArrayList<Classify>();
list.add(selectById);
Result result = new Result();
result.setRows(list);
return result;
}
@Override
public Result delete( List<String> ids) {
Result result =new Result();
try {
mapping.deleteBatchIds(ids);
} catch (Exception e) {
result.setCode(1);
result.setMsg("删除失败");
}
return result;
}
@Override
public Result save(Classify classify) {
Result result =new Result();
String string =classify.getClassifyName();
String []split=string.split(",");
if(split.length==1) {
try {
// 将所有的一级分类的名字查出来
List<Classify> rows = mapping.classifyQuery();
for (Classify entity : rows) {
if(split[0].equals(entity.getClassifyName())) {
throw Exception;
}
}
classify.setClassifyName(split[0]);
mapping.insert(classify);
} catch (Exception e) {
result.setCode(1);
result.setMsg("该类已存在");
}
}else {
try {
// 将已知一级分类下的二级分类的名字查出来
List<Classify> rows = mapping.classifyNameID(split[1]);
for (Classify entity : rows) {
if(split[0].equals(entity.getClassifyName())) {
throw Exception;
}
}
classify.setClassifyName(split[0]);
classify.setClassifySire(new Integer(split[1]));
mapping.insert(classify);
} catch (Exception e) {
result.setCode(1);
result.setMsg("该类已存在");
}
}
return result;
}
@Override
public Result update(Classify classify,Integer classifyNames) {
/*
* 修改
* 可能会将数据修改为二级分类或者一级分类
* */
Result result = new Result();
classifyNames=classifyNames==null?0:classifyNames;
try {
classify.setClassifySire(classifyNames);
mapping.updateById(classify);
} catch (Exception e) {
result.setCode(1);
result.setMsg("错误"+e);
}
return result;
}
@Override
public Result queryTop() {
// 查询所有一级分类
Result result = new Result();
result.setRows(mapping.classifyQuery());
return result;
}
@Override
public Result queryTwo(String parentId) {
// 查询所有父类id是指定值的数据
Result result = new Result();
result.setRows(mapping.classifyNameID(parentId));
return result;
}
}
集成mybatis plus使用的接口
package cn.et.wk.manager.shopping.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import cn.et.wk.manager.shopping.entity.Classify;
@Mapper
public interface ClassMapper extends BaseMapper<Classify>{
public List<Classify> classifyQuery();
public List<Classify> classifyNameID(String parentId);
}
配置xml文件
<?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="cn.et.wk.manager.shopping.mapper.ClassMapper">
<resultMap type="cn.et.wk.manager.shopping.entity.Classify"
id="classify">
<result property="commodityCategoryNo" column="commodity_category_no"/>
<result property="classifyName" column="commodity_category_name"/>
<result property="classifySort" column="commodity_category_sort"/>
<result property="classifySire" column="commodity_category_sire"/>
<result property="createBy" column="commodity_category_user"/>
<result property="createTime" column="commodity_category_time"/>
<result property="lastUpdateBy" column="last_modification_user"/>
<result property="lastUpdateTime" column="last_modification_time"/>
</resultMap>
<select id="classifyQuery" resultMap="classify">
select * from td_commodity_category where commodity_category_sire=0
</select>
<select id="classifyNameID" resultMap="classify" parameterType="String">
select * from td_commodity_category where commodity_category_sire=#{0}
</select>
</mapper>
前台代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="/resource/css/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="/resource/css/themes/icon.css">
<link rel="stylesheet" type="text/css" href="/resource/css/demo/demo.css">
<script type="text/javascript" src="/resource/js/jquery.min.js"></script>
<script type="text/javascript" src="/resource/js/jquery.easyui.min.js"></script>
<script type="text/javascript" src="/resource/js/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="/resource/js/common.js"></script>
<script>
$(function(){
$('#mytable').treegrid({
url:'/shopping/classify/query', //访问后台的地址
idField:'id',
treeField:'region',
pagination: true,//是否开启分页,默认是false
rownumbers:true,//设置表格行好如果为true,则显示一个行号列。
singleSelect: true,//是否可以多选默认是false
singleSelect:false,
sortName:'pid',
sortOrder:'asc',
remoteSort:false,//排序
method:'get',
columns:[[
{field:'xxx',title:'xxx',width:100,checkbox:true},
{field:'id',title:'商品类别编号', width:100,align:'center'},
{field:'region',title:'商品类别名称', width:400,align:'left'},
{field:'pid',title:'排序', width:100,align:'center'},
{field:'xx',title:'操作',width:100,align:'center',
formatter: function(value,row,index){
return "<a href='javascript:void(0)' onclick='update(this)'>修改</a>"+
"-"+
"<a href='javascript:void(0)' onclick='del(\""+row.id+"\")'>删除</a>";
}
}
]]
});
/*添加时用到的类别 (增加按钮) */
$("#addClass").click(function(){
$('#win #fm').form('clear');
$("#win #dlg-buttons-edit").hide();
$("#win #dlg-buttons-save").show();
var selected = $('#mytable').datagrid('getSelections');
if(selected.length==0){
$('#win #fm div #top').combobox({ disabled: true });
}else if(selected.length==1){
var nodes = $("#mytable").treegrid("getParent", selected[0].id);
if(selected[0]['_parentId']==0){
$('#win #fm div #top').combobox({ disabled: false });
$('#win #fm div #top').combobox('select',selected[0].id);
}else if(nodes['_parentId']!=0){
$.messager.alert('警告','不能在该分类中添加子类 ');
return false;
}else{
$('#win #fm div #top').combobox({ disabled: false });
$('#win #fm div #top').combobox('select',selected[0]['_parentId']);
}
}else{
$.messager.alert('警告','只能选择一个类别进行添加');
return false;
}
$('#win').dialog('open');
})
/*二级联动 */
$('#win #fm div #top').combobox({
url:'/shopping/classify/queryTopClass',
type:'post',
valueField:'commodityCategoryNo',
textField:'classifyName' ,
});
// 修改表单需要用到的二级联动
$('#wins #fms div #top').combobox({
url:'/shopping/classify/queryTopClass',
type:'post',
valueField:'commodityCategoryNo',
textField:'classifyName' ,
});
//提交表单
$("#win #fm #dlg-buttons-save #confirm-save").click(function(){
var isValid = $("#win #fm").form('validate');
if(isValid){
if($("#win #fm #sort").val() == ""){
$("#win #fm #sort").val("0");
}
$('#win #fm div #number').remove();
$.ajax({
type: 'POST',
url: '/shopping/classify/save',
dataType : 'json',
data:$('#win #fm').serialize(),
success: function (result) {
if(result.code == 0){
$.messager.alert('确定','添加成功');
$('#win').dialog('close');
}else{
$.messager.alert('警告','该类名已存在');
}
}
})
$('#mytable').treegrid('load');
}else{
$.messager.show({
title:'请注意 ',
msg:'该类别不能没有名字!',
showType:'show',
timeout:1500,
style:{
right:'',
top:document.body.scrollTop+document.documentElement.scrollTop,
bottom:''
}
});
}
});
//修改按钮
$("#wins #fms #dlg-buttons-edit #confirm-edit").click(function(){
$.ajax({
type: 'put',
url: 'update',
dataType : 'json',
data:$(' #fms').serialize(),
success: function (result) {
if(result.code == 0){
$.messager.alert('确定','修改成功');
$('#wins').dialog('close');
}else{
$.messager.alert('警告','错误'+result.msg);
}
}
})
$('#mytable').treegrid('load');
});
})
//删除单个
function del(){
$.messager.confirm('确认','您确认想要删除该分类吗?',function(r){
var selectedRow = $('#mytable').treegrid('getSelected');
if (r){
var a = $('#mytable').treegrid('getChildren',selectedRow.id);
$('#mytable').treegrid('remove',selectedRow.id);
var ids = [];
for(var i=0; i<a.length; i++){
ids[i] = a[i].id;
}
$.ajax({
type: 'delete',
dataType: 'json',
url:"/shopping/classify/delete/"+selectedRow.id,
data: JSON.stringify(ids),
contentType:"application/json",
success: function (result) {
if(result.code==0){
$.messager.alert('确认','删除成功');
}else{
$.messager.alert('警告','删除失败');
}
}
});
}
})
}
//删除多个
function deleteAll(){
$.messager.confirm('确认','您确认想要删除所选中的分类吗?',function(r){
if (r){
var ids = [];
var arrayId = $('#mytable').datagrid('getSelections');
console.log(arrayId);
for(var i=0; i<arrayId.length; i++){
var nodes = $("#mytable").treegrid("getParent", arrayId[i].id);
if(arrayId[i]['_parentId']==0){
ids.push(arrayId[i].id); // 拿到一级分类的id
var children = $("#mytable").treegrid("getChildren", arrayId[i].id); // 将一级分类的子类找出来
for(var index=0; index<children.length; index++){
ids.push(children[index].id); // 获取一级分类下的所有子类
var son = $("#mytable").treegrid("getChildren",children[index].id);
for(var a=0; a<son.length; a++){
ids.push(son[a].id);
}
}
}else if(nodes['_parentId']!=0){
ids.push(arrayId[i].id);
}else{
ids.push(arrayId[i].id);
var children = $("#mytable").treegrid("getChildren", arrayId[i].id);
for(var index=0; index<children.length; index++){
ids.push(children[index].id);
}
}
}
var newIds = [];
$.each(ids,function(index,value){
if($.inArray(value,newIds)==-1){
$('#mytable').treegrid('remove',value);
newIds.push(value);
}
})
$.ajax({
type: 'delete',
dataType: 'json',
url:"/shopping/classify/deleteAll",
data: JSON.stringify(newIds),
contentType:"application/json",
success: function (result) {
if(result.code==0){
$.messager.alert('确认','删除成功');
}else{
$.messager.alert('警告','删除失败');
}
}
})
$('#mytable').treegrid('load');
}
});
}
//修改事件
function update(_this){
$.messager.confirm('确认','是否修改该类别 ?',function(r){
if (r){
$('#wins #fms').form('clear');
$("#wins #dlg-buttons-edit").show();
$("#wins #dlg-buttons-save").hide();
$("#divtop").show();
// 获取当前选中的行
//var node = $('#myTable').treegrid('getSelected');
var id = $(_this).parents('tr').eq(0).children().eq(1).text();
//获取当前选中行的父类
var parent = $("#mytable").treegrid("getParent", id);
var vv=[],ss=[];
// 获取当前选中行的父类的父类
//var getRoot = $("#mytable").treegrid("getParent", parent.id);
$('#wins #fms div #top').combobox({ disabled: false });
$.ajax({
type: 'GET',
url:'/shopping/classify/queryId/'+id,
success: function (result) {
var classifySire=result[0].classifySire;
if(classifySire==0){
$("#divtop").hide();
}
$('#fms').form('load',result[0]);
//$('#win #fm div #top').combobox('select',getRoot.id);
}
})
$('#wins').dialog('open');
}
})
}
</script>
</head>
<body>
<div class="div">
<span class="title">商品类别管理</span>
<span class="png"><img src="../../api/jQueryEasyUI/jquery-easyui-1.3.6/themes/icons/add.png"></span>
<a href="#" id="addClass">添加类别</a>
</div><br/>
<table id="mytable" fitColumns="true" ></table>
<input class="del" type="button" value="删除所选" onclick="deleteAll()"/>
<div id="win" class="easyui-dialog" title="添加类别" style="width: 300px; padding: 10px 20px; height: 240px;" closed="true" buttons="#dlg-buttons">
<form id="fm" method="post">
<div style="display:none">
<label>编号:</label>
<input id="number" name="commodityCategoryNo"/>
</div>
<div >
<label>类别名称:</label>
<input id="class_name" name="classifyName" class="easyui-validatebox" data-options="required:true,missingMessage:'类别名不能为空'" />
</div><br/>
<div>
<label>一级分类:</label>
<input id="top" class="easyui-combobox" data-options="editable:false" name="classifyName">
</div><br/>
<div>
<label> 排序:</label>
<input id="sort" name="classifySort" required="true" class="easyui-textbox"/>
</div><br/>
<div id="dlg-buttons-save" style="display:none" >
<a id="confirm-save" class="easyui-linkbutton c6" iconcls="icon-ok" style="width: 90px">提交</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-cancel" onclick="javascript:$('#win').dialog('close')" style="width: 90px">取消</a>
</div>
</form>
</div>
<div id="wins" name="_method" value="PUT" class="easyui-dialog" title="修改类别" style="width: 300px; padding: 10px 20px; height: 240px;" closed="true" buttons="#dlg-buttons">
<form id="fms">
<div style="display:none">
<label>编号:</label>
<input id="number" name="commodityCategoryNo"/>
</div>
<div >
<label>类别名称:</label>
<input id="class_name" name="classifyName" class="easyui-validatebox" data-options="required:true,missingMessage:'类别名不能为空'" />
</div><br/>
<div id="divtop">
<label>一级分类:</label>
<input id="top" class="easyui-combobox" data-options="editable:false" name="classifyNames">
</div><br/>
<div>
<label> 排序:</label>
<input id="sort" name="classifySort" required="true" class="easyui-textbox"/>
</div><br/>
<div id="dlg-buttons-edit" style="display:none">
<a id="confirm-edit" href="javascript:void(0)" class="easyui-linkbutton c6" iconcls="icon-ok" style="width: 90px">修改</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-cancel" onclick="javascript:$('#win').dialog('close')" style="width: 90px">取消</a>
</div>
</form>
</div>
</body>
</html>
最后效果