1. 程式人生 > >Easyui DataGrid增刪改查實現

Easyui DataGrid增刪改查實現

Java使用Spring MVC以及Mybatis實現 DataGrid的增刪改查/分頁,以Mysql資料庫為例,效果:

具體程式碼如下:

0、資料庫指令碼:

CREATE TABLE `compy` (
  `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵ID',
  `compy_id` varchar(64) NOT NULL COMMENT '供應商ID',
  `compy_name` varchar(512) NOT NULL COMMENT '供應商名稱[如:泰康]',
  `remark` varchar(1024) DEFAULT NULL COMMENT '備註',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '資料更新時間',
  `create_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '資料建立時間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COMMENT='供應商配置表';

1、前端頁面:

<div class="easyui-layout" data-options="fit:true,border:false">
	<div id="searchCompanyUrl" style="padding:3px">
		<div class="comp-search-box">
				<div class="screen-top">
					<div class="colRow">
						<input id="s_compyName" type="text" class="easyui-textbox" name="compyName" data-options="label:'供應商名稱:'" />
					</div>
					<div class="colRow">
						<button class="easyui-linkbutton btnDefault" onclick="dosearchCompanyUrl();">
							<i class="fa fa-search"></i>查詢
						</button>
					</div>
				</div>

			</div>
			<div class="btnbar-tools">
				<a href="javascript:;" class="add" id="newCompy"><i class="fa fa-plus-square success"></i>新增</a>
				<a href="javascript:;" class="del" id="delCompy"><i class="fa fa-times-rectangle danger"></i>刪除</a>
			</div>
	</div>
	
    <div data-options="region:'center',border:false"  style="overflow: hidden;">
       <table id="companyGrid"></table>
    </div>
</div>

2、JS相關:

<script type="text/javascript">
$(document).ready(function(){	

	//刪除確認
	$('#delCompy').click(function(){
		var selRow = $('#companyGrid').datagrid('getSelections');  
		if(selRow.length<=0){
			layer.msg('請選擇要刪除的資料!')
		}else{
			layer.confirm('<div class="delMsgTip"><div class="delTip"><i class="icon"></i>你確定要刪除當前資料!<br>是“確認”,否“取消”</div></div>', {type:0, title:false, shade:0}, function(index){
				var ids=[];
				for (var i = 0; i < selRow.length; i++) {
					var id=selRow[i].id;   
					ids.push(id); 
				}
				var paramIds = ids.join(','); 
				var basePath = $("#basePath").val();
				$.ajax({
						cache : true,
						type : "POST",
						url : basePath+"/compy/delCompy",
						data : { ids: paramIds },
						async : false,
						error : function(request) {
							layer.msg('網路錯誤,請稍後再試!')
						},
						success : function(data) {
							if(data=='success'){
								dosearchCompanyUrl();
								layer.msg('刪除成功!')
								$("#companyGrid").datagrid("clearChecked");
								$("#companyGrid").datagrid("clearSelections");
							}else{
								layer.msg('刪除失敗!');
							}
						}
				 });
			});
		}
	});
	
	//載入列表
	var companyGrid = $('#companyGrid').datagrid({
		url : basePath+'/compy/getCompyList',
		idField : 'id',
		fit : true,
		fitColumns : true, //列寬自適應false
		border : true, //邊框
		nowrap:true,
		rownumbers : true,
		pageSize:20,//初始化顯示條數  
		pageList: [20,50,100],
		pagination : true,
		singleSelect:false,
		toolbar:"#searchCompanyUrl",
		frozenColumns : [ [ {
			title : 'id',
			field : 'id',
			width : 40,
			hidden : true
		} ] ],
		columns : [ [ { 
			field:'id',checkbox:true 
		},{
			field : 'compyId',
			title : '供應商編號',
			width : 150
		},{
			field : 'compyName',
			title : '供應商名稱',
			width : 150
		},{
			field : 'remark',
			title : '備註',
			width : 150
		},{
			field : 'createTime',
			title : '資料建立時間',
			width : 150
		} ] ]
	});
});

//搜尋
function dosearchCompanyUrl(){
	$('#companyGrid').datagrid('load',{
		companyName: $('#s_compyName').val()
	});
}


//新增儲存提交
function add(){
	basePath = $("#basePath").val();
	var validate = $("#formAddCompany").form('validate');
	if(validate){
		$.ajax({
			cache : true,
			type : "POST",
			url : basePath+"/compy/addCompy",
			data : $('#formAddCompany').serialize(),
			async : false,
			error : function(request) {
				layer.msg('網路錯誤,請稍後再試!')
			},
			success : function(data) {
				if(data=='success'){
					layer.closeAll();
					dosearchCompanyUrl();
					layer.msg('新增成功!')
				}else{
					layer.msg('新增失敗!')
				}
			}
		});
	}
}
function clearCompanyForm(){//重置表單
	$('#formAddCompany').form('clear');
}
</script>

3、Controller實現

/**
 * @ClassName: CompyController
 * @Description: Controller配置
 * @author sam
 * @date 2018年9月25日 下午4:03:23
 */
@Controller
@RequestMapping("/compy")
public class CompyController {

	@Autowired
	private compyService compyService;

	// 查詢列表
	@PostMapping("/getCompyList")
	@ResponseBody
	public DataGrid getCompyList(PageUtils page, String companyName) {
		List<HeiniuCompy> dataList = compyService.getCompyList(page, companyName);
		int total = compyService.getCompyCount(companyName);
		DataGrid result = new DataGrid(total, dataList);
		return result;
	}

	// 新增
	@PostMapping("/addCompy")
	@ResponseBody
	public String addCompy(CompyDto compyDto) {
		// 儲存
		int result = compyService.addCompy(compyDto);
		if (result > 0) {
			return "success";
		} else {
			return "fail";
		}
	}

	// 刪除
	@PostMapping("/delCompy")
	@ResponseBody
	public String delCompy(String ids) {
		if (StringUtils.isEmpty(ids)) {
			throw new RuntimeException("引數為空");
		}
		int result = compyService.delCompy(ids);
		if (result > 0) {
			return "success";
		} else {
			return "fail";
		}
	}

}

4、DataGrid工具類

/**
 * @ClassName: DataGrid
 * @Description: DataGrid工具類
 * @author sam
 * @date 2018年9月22日 下午5:11:05
 */
public class DataGrid {

	private int total;
	private List<?> rows;
	// 頁尾
	private List<?> footer;

	public DataGrid(int total, List<?> rows, List<?> footer) {
		super();
		this.total = total;
		this.rows = rows;
		this.footer = footer;
	}

	public DataGrid(int total, List<?> rows) {
		super();
		this.total = total;
		this.rows = rows;
	}

	public DataGrid() {
		super();
		// TODO Auto-generated constructor stub
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public List<?> getRows() {
		return rows;
	}

	public void setRows(List<?> rows) {
		this.rows = rows;
	}

	public List<?> getFooter() {
		return footer;
	}

	public void setFooter(List<?> footer) {
		this.footer = footer;
	}

}

5、PageUtils分頁工具類
 

/**
 * @ClassName: PageUtils 
 * @Description: 分頁物件
 * @author sam 
 * @date 2018年9月20日 下午5:48:24
 */
public class PageUtils {

    private int page; // 當前頁數
    private int rows; // 每行顯示條數

    public PageUtils(int page, int rows) {
        super();
        this.page = page;
        this.rows = rows;
    }

    public PageUtils() {
        super();
        // TODO Auto-generated constructor stub
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }
}

6、Service層業務實現

@Autowired
private CompyDao compyDao;
	
@Override
public List<Compy> getCompyList(PageUtils page, String companyName) {
	List<Compy> list = new ArrayList<Compy>();
	try {
		list = compyDao.selectCompyByPage((page.getPage() - 1) * page.getRows(), page.getRows(), companyName);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return list;
}

@Override
public int getCompyCount(String companyName) {
	int total = 0;
	try {
		total = compyDao.selectCompyCount(companyName);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return total;
}

@Override
public int addCompy(CompyDto compyDto) {
	int result = 0;
	try {
		Compy compy = new Compy();
		BeanUtil.copyProperties(compyDto, compy);
		compy.setCompyId(UUID.randomUUID().toString());
		compy.setCreateTime(new Date());
		compy.setUpdateTime(new Date());

		result = compyDao.insert(compy);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return result;
}

@Override
public int delCompy(String ids) {
	int result = 0;
	try {
		String[] array = ids.split(",");
		result = compyDao.delCompy(array);
	} catch (Exception e) {	
		e.printStackTrace();
	}
	return result;
}

7、Mybatis CompyDao實現:

/**
 * @ClassName: CompyDao
 * @Description:Dao實現
 * @author sam
 * @date 2018年9月25日 下午3:28:23
 */
public interface CompyDao extends CompyMapper {

	// 刪除記錄
	int delCompy(@Param("array") String[] ids);

	// 查詢列表(分頁)
	List<Compy> selectCompyByPage(@Param("index") int index, @Param("rows") int rows,
			@Param("compy_name") String compyName);

	// 查詢總數(分頁)
	int selectCompyCount(@Param("compy_name") String compyName);

	// 查詢名稱下拉列表
	List<Compy> selectCompanyNameList();
}

8、Mybatis CompyDAO.xml實現

<select id="selectCompyByPage" resultMap="com.sam.generator.mapper.CompyMapper.BaseResultMap">
    select * 
    from compy
   <where>
      <if test="compy_name!=null and compy_name!=''">
        and compy_name like #{compy_name}
      </if>
   </where>
   order by create_time desc
   limit #{index},#{rows};
</select>

<select id="selectCompyCount" resultType="Integer">  
   select count(*) 
   from  compy 
   <where>
      <if test="compy_name!=null and compy_name!=''">
        and compy_name like #{compy_name}
      </if>
   </where>
</select>  

<delete id="delCompy">
	delete from compy where id in 
	<foreach item="idItem" collection="array"  open="(" separator="," close=")">
	#{idItem}
	</foreach>
</delete>

以上為主要配置完成!spring相關配置這裡就不記錄了,啟動,執行。