MyBatis+Gson+Jersey+EasyUI的增删改例子
增删改查的例子,做个备忘记录,这里用的是MySQL,这里未用自增主键,为了少量数据实时修改编辑的需要
创建表
CREATE TABLE `li_s_sjzx_skfs` (
`BH` int(11) NOT NULL,
`MC` varchar(50) DEFAULT NULL,
`BM` varchar(10) DEFAULT NULL,
`PYJM` varchar(20) DEFAULT NULL,
`PX` int(11) DEFAULT NULL,
`YXBZ` tinyint(1) DEFAULT NULL,
`BZ` varchar(200) DEFAULT NULL,
`XGR` varchar(20) DEFAULT NULL,
`XGRQ` datetime DEFAULT NULL,
`TBR` varchar(20) DEFAULT NULL,
`TBRQ` datetime DEFAULT NULL,
PRIMARY KEY (`BH`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 PACK_KEYS=0;
INSERT INTO `li_s_sjzx_skfs` VALUES (‘1’, ‘现金’, null, null, ‘0’, null, ”, ”, ‘2015-10-10 09:33:55’, ”, ‘2015-10-10 09:33:55’);
INSERT INTO `li_s_sjzx_skfs` VALUES (‘2’, ‘支票’, null, null, ‘0’, null, ”, ”, ‘2015-10-10 09:34:08’, ”, ‘2015-10-10 09:34:08’);
1.MyBatis 设置
1.1MyBatis数据库配置
<?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>
<typeAliases>
<typeAlias alias=”Skfs” type=”com.li.sjzx.Skfs” />
<typeAlias alias=”SkfsSelectPage” type=”com.li.sjzx.SkfsSelectPage” />
</typeAliases>
<environments default=”development”>
<environment id=”development”>
<transactionManager type=”JDBC” />
<dataSource type=”POOLED”>
<property name=”driver” value=”com.mysql.jdbc.Driver” />
<property name=”url”
value=”jdbc:mysql://127.0.0.1:3306/lics?characterEncoding=utf8″ />
<property name=”username” value=”root” />
<property name=”password” value=”…..” />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource=”com/li/sjzx/Skfs.xml” />
</mappers>
</configuration>
1.2MyBatis配置读取
package com.li.mybatis;
import java.io.Reader;
public class MyBatisConfig {
private static class SingletonHolder{
private static final MyBatisConfig INSTANCE = new MyBatisConfig();
}
public static MyBatisConfig getInstance(){
return SingletonHolder.INSTANCE;
}
private void Configuration() {
}
// @Getter @Setter
private String xmlPath;
public String getXmlPath() {
return xmlPath;
}
public void setXmlPath(String xmlPath) {
this.xmlPath = xmlPath;
}
}
1.3MyBatis的公共类
package com.li.mybatis;
//import lombok.Getter;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisSqlSessionFactorySingletonHolder {
static class InnerHolder{
private static final MyBatisSqlSessionFactorySingletonHolder INSTANCE;
static {
try {
INSTANCE = new MyBatisSqlSessionFactorySingletonHolder();
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
}
public static MyBatisSqlSessionFactorySingletonHolder getInstance(){
return InnerHolder.INSTANCE;
}
private MyBatisSqlSessionFactorySingletonHolder() throws Exception {
init();
}
private void init() throws Exception {
// log = LoggerFactory.getLogger(getClass());
Reader reader = null;
try {
reader = Resources.getResourceAsReader(MyBatisConfig.getInstance().getXmlPath());
factory = new SqlSessionFactoryBuilder().build(reader);
// System.out.println(“SqlSessionFactoryBuilder OK”);
}catch(Exception ex){
// log.error(ex.getMessage(),ex);
throw ex;
} finally {
try {
if(reader != null){
reader.close();
}
} catch (IOException ex) {
// log.error(ex.getMessage(),ex);
}
}
}
// @Getter
private SqlSessionFactory factory;
// private Logger log;
public SqlSessionFactory getFactory() {
return factory;
}
}
2.Gson的设置
package com.li.json;
import java.lang.reflect.Type;
import java.text.DateFormat;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonUtils {
public static String bean2json(Object bean) {
Gson gson = new GsonBuilder().setDateFormat(“yyyy-MM-dd HH:mm:ss”).setPrettyPrinting().create();
return gson.toJson(bean);
}
public static <T> T json2bean(String json, Type type) {
Gson gson = new GsonBuilder().setDateFormat(“yyyy-MM-dd HH:mm:ss”).create();
return gson.fromJson(json, type);
}
}
3.Jersey的配置
3.1 web.xml
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.li.jersey.JerseyApp</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/jersey/*</url-pattern>
</servlet-mapping>
3.2 用一个公共包注册类包
package com.li.jersey;
import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.ResourceConfig;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
@ApplicationPath(“/jersey”)
public class JerseyApp extends ResourceConfig {
public JerseyApp() {
packages(“com.li.sjzx”);
register(JacksonJsonProvider.class);
}
}
4.模块功能整合方法
4.1接口类
package com.li.sjzx;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public interface ISkfsOperaction {
public int getNextId();
public void appendData(Skfs skfs);
public void updateData(Skfs skfs);
public void deleteData(int bh);
public List<Skfs> selectData(String mc);
public List<Skfs> selectPageData(SkfsSelectPage cx);
public int selectPageTotalData(SkfsSelectPage cx);
}
4.2 Bean类
package com.li.sjzx;
import java.util.Date; //import java.sql.Date;
import java.sql.*;
public class Skfs {
private int bh;
private String mc;
private String bm;
private String pyjm;
private int px;
private Boolean yxbz;
private String bz;
private String xgr;
private Date xgrq;
private String tbr;
private Date tbrq;
public int getBh() {
return bh;
}
public void setBh(int bh) {
this.bh = bh;
}
public String getMc() {
return mc;
}
public void setMc(String mc) {
this.mc = mc;
}
public String getBm() {
return bm;
}
public void setBm(String bm) {
this.bm = bm;
}
public String getPyjm() {
return pyjm;
}
public void setPyjm(String pyjm) {
this.pyjm = pyjm;
}
public int getPx() {
return px;
}
public void setPx(int px) {
this.px = px;
}
public Boolean getYxbz() {
return yxbz;
}
public void setYxbz(Boolean yxbz) {
this.yxbz = yxbz;
}
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz;
}
public String getXgr() {
return xgr;
}
public void setXgr(String xgr) {
this.xgr = xgr;
}
public Date getXgrq() {
return xgrq;
}
public void setXgrq(Date xgrq) {
this.xgrq = xgrq;
}
public String getTbr() {
return tbr;
}
public void setTbr(String tbr) {
this.tbr = tbr;
}
public Date getTbrq() {
return tbrq;
}
public void setTbrq(Date tbrq) {
this.tbrq = tbrq;
}
}
4.3分页类
package com.li.sjzx;
public class SkfsSelectPage {
String bh;
String mc;
int pagePostion;
int pageSize;
public String getBh() {
return bh;
}
public void setBh(String bh) {
this.bh = bh;
}
public String getMc() {
return mc;
}
public void setMc(String mc) {
this.mc = mc;
}
public int getPagePostion() {
return pagePostion;
}
public void setPagePostion(int pagePostion) {
this.pagePostion = pagePostion;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}
4.4模块功能之MyBatis的SQL配置 skfs.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=”com.li.sjzx.ISkfsOperaction”>
<select id=”getNextId” resultType=”int”>
SELECT IFNULL(MAX(BH),-1) AS NextId FROM LI_S_SJZX_SKFS
</select>
<!– 为了返回list 类型而定义的returnMap –>
<resultMap type=”Skfs” id=”resultListSkfs”>
<result column=”BH” property=”bh” />
<result column=”MC” property=”mc” />
<result column=”BM” property=”bm” />
<result column=”PYJM” property=”pyjm” />
<result column=”PX” property=”px” />
<result column=”YXBZ” property=”yxbz” />
<result column=”BZ” property=”bz” />
</resultMap>
<select id=”selectData” parameterType=”string” resultMap=”resultListSkfs”>
select * from LI_S_SJZX_SKFS WHERE MC like #{mc}
</select>
<select id=”selectPageData” parameterType=”SkfsSelectPage”
resultMap=”resultListSkfs”>
select * from LI_S_SJZX_SKFS where BH like #{bh} and MC like #{mc}
limit
#{pagePostion},#{pageSize}
</select>
<select id=”selectPageTotalData” parameterType=”SkfsSelectPage”
resultType=”int”>
SELECT count(*) As SL FROM LI_S_SJZX_SKFS WHERE BH like #{bh} and MC like #{mc}
</select>
<insert id=”appendData” parameterType=”Skfs” useGeneratedKeys=”false”
keyProperty=”bh”>
insert into LI_S_SJZX_SKFS(BH,MC,BM,PYJM,PX,YXBZ,BZ,XGR,XGRQ,TBR,TBRQ)
values(#{bh},#{mc},#{bm},#{pyjm},#{px},#{yxbz},#{bz},
#{xgr},#{xgrq,jdbcType=VARCHAR},#{tbr},#{tbrq,jdbcType=VARCHAR})
</insert>
<update id=”updateData” parameterType=”Skfs”>
update LI_S_SJZX_SKFS
set BH=#{bh}, MC=#{mc},BM=#{bm},PYJM=#{pyjm},
px=#{px},yxbz=#{yxbz},BZ=#{bz},
XGR=#{xgr},XGRQ=#{xgrq,jdbcType=VARCHAR}
where BH=#{bh}
</update>
<delete id=”deleteData” parameterType=”int”>
delete from LI_S_SJZX_SKFS where BH=#{bh}
</delete>
</mapper>
4.4 jerysey服务的实现
package com.li.sjzx;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.QueryParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.Reader;
import java.util.List;
import java.util.Date;
import com.li.json.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.google.common.collect.Multiset.Entry;
import com.li.msg.SMessage;
import com.li.mybatis.*;
import com.li.jersey.*;
@Path(“sjzx/skfs”)
public class SkfsResource {
// —————————-
@Path(“getListPageData”)
@POST
// @Produces( {MediaType.APPLICATION_XML })
@Produces(value = MediaType.APPLICATION_JSON)
public String getListPageData(@FormParam(“page”) int page,@FormParam(“rows”) int rows,
@Context HttpServletRequest request,
@FormParam(“bh”) String bh,
@FormParam(“mc”) String mc ) {
System.out.println(“getList—-Data———-“);
System.out.println(this.getClass().getName());
try {
HttpSession hs = ((HttpServletRequest) request).getSession();
String path = ((HttpServletRequest) request).getContextPath();
if (hs.getAttribute(“userdm”) != null) {
System.out.println(“userdm=” + hs.getAttribute(“userdm”));
System.out.println(“usermc=” + hs.getAttribute(“usermc”));
}
} catch (Exception e) {
System.out.println(“request getparamer Session Error”);
}
try {
System.out.println(“FormParam rows:” + rows);
System.out.println(“FormParam page:” + page);
} catch (Exception e) {
System.out.println(“FormParam Error”);
}
String bh_cx=”%”;
String mc_cx=”%”;
System.out.println(“bh=”+bh);
System.out.println(“mc=”+mc);
if(bh==null||bh.equals(“”)){
bh_cx=”%”;
}else{
bh_cx=”%”+bh+”%”;
}
if(mc==null||mc.equals(“”)){
mc_cx=”%”;
}else{
mc_cx=”%”+mc+”%”;
}
int pagePostion = 0;
int pageSize = 10;
try {
pagePostion = (page – 1) * rows;
pageSize = rows;
} catch (Exception e) {
pagePostion = 0;
pageSize = 10;
}
System.out.println(“pagePostion:” + pagePostion);
System.out.println(“pageSize:” + pageSize);
String jsonStr = “”;
List<Skfs> listFwry = new ArrayList<Skfs>();
try {
MyBatisConfig.getInstance().setXmlPath(“Configuration.xml”);
MyBatisSqlSessionFactorySingletonHolder factoryHolder = MyBatisSqlSessionFactorySingletonHolder
.getInstance();
SqlSession session = factoryHolder.getFactory().openSession();
// SqlSession session = sqlSessionFactory.openSession();
try {
try {
ISkfsOperaction SkfsOperation = session
.getMapper(ISkfsOperaction.class);
SkfsSelectPage cx = new SkfsSelectPage();
cx.setBh(bh_cx);
cx.setMc(mc_cx);
cx.setPagePostion(pagePostion);
cx.setPageSize(pageSize);
listFwry = SkfsOperation.selectPageData(cx);
int total = 0;
total = SkfsOperation.selectPageTotalData(cx);
Map<String, Object> jsonMap = new HashMap<String, Object>();// 定义map
//
jsonMap.put(“total”, total); // total 存放总记录数,必须的
jsonMap.put(“rows”, listFwry);// rows 存放每页记录 list
jsonStr = JsonUtils.bean2json(jsonMap);
System.out.println(jsonStr);
} catch (Exception e) {
System.out.println(“获取列表出错”);
e.printStackTrace();
}
} finally {
session.close();
}
} catch (Exception e) {
// return msg;
System.out.println(“错误.”);
}
return jsonStr;
}
// —————————-
@Path(“appendData”)
@POST
@Produces(value = { MediaType.APPLICATION_JSON + “;charset=utf-8” })
public SMessage appendData(Skfs skfs, @Context HttpServletRequest request) {
System.out.println(“——————“);
System.out.println(“———-skfs——–“);
String usermc=””;
try{
HttpSession hs =((HttpServletRequest)request).getSession();
if (hs.getAttribute(“userdm”) != null){
usermc=hs.getAttribute(“usermc”).toString();
System.out.println(“userdm=”+hs.getAttribute(“userdm”));
System.out.println(“usermc=”+hs.getAttribute(“usermc”));
}
}catch(Exception e ){
System.out.println(“request getparamer Session Error”);
}
// System.out.println(“request parameter:”+URLEncoder.encode(request.getParameter(“a”)));
System.out.println(“Append “);
// System.out.println(hts.toString());
SMessage msg = new SMessage();
msg.setId(0);
msg.setMsg(“错误”);
msg.setOther(“”);
try {
MyBatisConfig.getInstance().setXmlPath(“Configuration.xml”);
MyBatisSqlSessionFactorySingletonHolder factoryHolder = MyBatisSqlSessionFactorySingletonHolder
.getInstance();
SqlSession session = factoryHolder.getFactory().openSession();
// SqlSession session = sqlSessionFactory.openSession();
try {
try {
ISkfsOperaction SkfsOperation = session
.getMapper(ISkfsOperaction.class);
System.out.println(“数据编号:” + skfs.getBh());
System.out.println(“名称:” + skfs.getMc());
System.out.println(“备注:” + skfs.getBz());
int bh = -1;
bh = SkfsOperation.getNextId();
if (bh <= 0) {
bh = 1;
} else {
bh = bh + 1;
}
skfs.setBh(bh);
System.out.println(“取得 数据iD:” + skfs.getBh());
skfs.setTbr(usermc);
skfs.setXgr(usermc);
skfs.setTbrq(new Date());
skfs.setXgrq(skfs.getTbrq());
SkfsOperation.appendData(skfs);
System.out.println(“当前增加的数据 Id=” + skfs.getBh());
session.commit();
msg.setId(1);
msg.setMsg(“成功.”);
msg.setOther(String.valueOf(skfs.getBh()));
System.out.println(“增加 数据ok”);
} catch (Exception e) {
System.out.println(“增加 数据出错”);
msg.setId(2);
msg.setMsg(“错误.”);
msg.setOther(“”);
e.printStackTrace();
}
} finally {
session.close();
}
// return msg;
} catch (Exception e) {
System.out.println(“错误.”);
msg.setId(0);
msg.setMsg(“错误”);
msg.setOther(“”);
e.printStackTrace();
}
return msg;
}
// —————————-
@Path(“updateData”)
@POST
// + “;charset=utf-8”
@Produces(value = { MediaType.APPLICATION_JSON + “;charset=utf-8” })
// public TestBean getJsonCs1(@Context HttpServletRequest request){
public SMessage updateData(Skfs Skfs, @Context HttpServletRequest request) {
System.out.println(“——————“);
System.out.println(“Update “);
SMessage msg = new SMessage();
msg.setId(0);
msg.setMsg(“错误”);
msg.setOther(“”);
try {
MyBatisConfig.getInstance().setXmlPath(“Configuration.xml”);
MyBatisSqlSessionFactorySingletonHolder factoryHolder = MyBatisSqlSessionFactorySingletonHolder.getInstance();
SqlSession session = factoryHolder.getFactory().openSession()
try {
try {
ISkfsOperaction SkfsOperation = session
.getMapper(ISkfsOperaction.class);
System.out.println(“数据编号:” + Skfs.getBh());
System.out.println(“名称:” + Skfs.getMc());
System.out.println(“备注:” + Skfs.getBz());
System.out.println(“Update:” + Skfs.getBh());
SkfsOperation.updateData(Skfs);
System.out.println(“当前修改数据 Id=” + Skfs.getBh());
session.commit();
msg.setId(1);
msg.setMsg(“成功.”);
msg.setOther(“”);
System.out.println(“修改 数据ok”);
} catch (Exception e) {
System.out.println(“修改 数据出错”);
msg.setId(2);
msg.setMsg(“错误.”);
msg.setOther(“”);
e.printStackTrace();
}
} finally {
session.close();
}
// return msg;
} catch (Exception e) {
// return msg;
System.out.println(“错误.”);
msg.setId(0);
msg.setMsg(“错误”);
msg.setOther(“”);
e.printStackTrace();
}
return msg;
}
// —————————-
@Path(“deleteData”)
@POST
@Produces(value = { MediaType.APPLICATION_JSON + “;charset=utf-8” })
public SMessage deleteData(@FormParam(“bh”) int bh,
@Context HttpServletRequest request) {
System.out.println(“——————“);
System.out.println(“request parameter:”
+ URLEncoder.encode(request.getParameter(“ywid”)));
System.out.println(“deleteFwry”);
System.out.println(“数据编号bh:” + bh);
SMessage msg = new SMessage();
msg.setId(0);
msg.setMsg(“错误”);
msg.setOther(“”);
try {
MyBatisConfig.getInstance().setXmlPath(“Configuration.xml”);
MyBatisSqlSessionFactorySingletonHolder factoryHolder = MyBatisSqlSessionFactorySingletonHolder.getInstance();
SqlSession session = factoryHolder.getFactory().openSession();
try {
try {
ISkfsOperaction SkfsOperation = session
.getMapper(ISkfsOperaction.class);
System.out.println(“当前删除的bh:” + bh);
SkfsOperation.deleteData(bh);
session.commit();
msg.setId(1);
msg.setMsg(“成功.”);
msg.setOther(“”);
System.out.println(“删除 数据OK”);
} catch (Exception e) {
System.out.println(“删除 数据出错”);
msg.setId(2);
msg.setMsg(“错误.”);
msg.setOther(“”);
e.printStackTrace();
}
} finally {
session.close();
}
} catch (Exception e) {
// return msg;
System.out.println(“错误.”);
msg.setId(0);
msg.setMsg(“错误”);
msg.setOther(“”);
e.printStackTrace();
}
return msg;
}
}
5.自定义服务消息类
package com.li.msg;
public class SMessage {
private int id;
private String msg;
private String other;
public SMessage() {
}
public SMessage(int id, String msg, String other) {
this.id = id;
this.msg = msg;
this.other = other;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getOther() {
return other;
}
public void setOther(String other) {
this.other = other;
}
}
5.前端EasyUI的实现
5.1skfsForm.js
function getDataByTj(){
var bh = $(“#cxbh”).val();
var mc = $(“#cxmc”).val();
$(‘#mygrid’).datagrid(‘load’,{
bh:bh,
mc: mc
});
}
function getRowIndex(target){
var tr = $(target).closest(‘tr.datagrid-row’);
return parseInt(tr.attr(‘datagrid-row-index’));
}
function formatAction(value,row,index){
var e = ‘<a href=”#” οnclick=”editRow(this)”>修改</a> ‘;
var d = ‘<a href=”#” οnclick=”deleteRow(this)”>删除</a>’;
return e+d;
}
$(function(){
$(‘#mygrid’).datagrid({
title:’档案’,
width:800,
height:500,
iconCls:’con-edit’,
toolbar: $(‘#tb’),
idField:’bh’,
fitColumns:’true’,
//fit:true,
rownumbers:true,
singleSelect:true,
pagination:true,
url:’../../../jersey/sjzx/skfs/getListPageData’,
method:’post’,
pageSize:10,
pageList:[ 10, 20, 30, 40 ],
columns:[[
{field:’ck’,checkbox:true},
{field:’bh’,title:’编号’,width:50 },
{field:’mc’,title:’名称’,width:80,editor:’text’},
{field:’bm’,title:’编码’,width:80,editor:’text’},
{field:’pyjm’,title:’拼音码’,width:80,editor:’text’},
{field:’px’,title:’排序’,width:80,editor:’text’},
{field:’yxbz’,title:’有效否’,width:80,editor:’text’},
{field:’bz’,title:’备注’,width:80,editor:’text’},
{field:’action’,title:’操作’,width:80,formatter:formatAction}
]],
onBeforeEdit:function(index,row){
},
onAfterEdit:function(index,row){
},
onCancelEdit:function(index,row){
}
});
});
function editRow(target){
// $(‘#mygrid’).datagrid(‘beginEdit’, getRowIndex(target));
// console.info(‘Edit data ‘);
var row = $(‘#mygrid’).datagrid(‘getData’).rows[getRowIndex(target)];
if (row) {
$(“#dlg”).dialog(“open”).dialog(‘setTitle’, ‘修改’);
$(“#fm”).form(“clear”);
$(“#fm”).form(“load”, row);
url = “UserManage.aspx?id=” + row.ID;
}else{
alert(“请先选择行.”);
}
}
function deleteRow(target){
$.messager.confirm(‘Confirm’,’确定要删除当前行吗?’,function(r){
if (r){
var row = $(‘#mygrid’).datagrid(‘getData’).rows[getRowIndex(target)];
//alert(“删除行bh=”+row.bh);
if(row.bh==-1){
// alert(“行为新增未保存行.”);
$(‘#mygrid’).datagrid(‘deleteRow’, getRowIndex(target));
}
else{
$.ajax({
url : “../../../jersey/sjzx/skfs/deleteData?ywid=001”,
type : “POST”,
data:”bh=”+row.bh,
dataType : “json”,
contentType : “application/x-www-form-urlencoded;charset=utf-8”,
async : false,
success : function(data) {
//alert(“success 返回值:”+data.id);
if (data.id==1){
$(‘#mygrid’).datagrid(‘deleteRow’, getRowIndex(target));
// alert(“删除成功”);
}
else
{
alert(“删除失败.”);
}
// 要提交的表单
},
error : function() {
alert(“删除error”);
}
});
}
}
});
}
function dataGridReload(){
$(‘#mygrid’).datagrid(‘reload’);
}
//appendRow
function appendRowTools(){
//
var data={};
data.bh=’-1′;
data.mc=’abc’;
var newData=$.toJSON(data);
$(“#dlg”).dialog(“open”).dialog(‘setTitle’, ‘新增’); ;
$(“#fm”).form(“clear”);
// $(‘#fm’).form(‘load’,data);
//$(‘#fm’).form(‘load’,{
// bh:’-1′,
// mc:’新增’,
// bz:”
//});
$(“#bh”).val(“-1”);
// document.getElementById(“hidtype”).value=”submit”;
}
//editRowTools
function editRowTools(){
var row = $(“#mygrid”).datagrid(“getSelected”);
if (row) {
$(“#dlg”).dialog(“open”).dialog(‘setTitle’, ‘修改’);
$(“#fm”).form(“clear”);
$(“#fm”).form(“load”, row);
url = “UserManage.aspx?id=” + row.ID;
}else{
alert(“请先选择行.”);
}
}
function deleteRowTools(){
$.messager.confirm(‘Confirm’,’确定要删除当前行吗?’,function(r){
if (r){
var row = $(“#mygrid”).datagrid(‘getSelected’);
if (row){
var rowIndex = $(“#mygrid”).datagrid(‘getRowIndex’, row);
if(row.bh==-1){
$(‘#mygrid’).datagrid(‘deleteRow’, rowIndex);
}
else{
$.ajax({
url : “../../../jersey/sjzx/skfs/deleteData?ywid=001”,
type : “POST”,
data:”bh=”+row.bh,
dataType : “json”,
contentType : “application/x-www-form-urlencoded;charset=utf-8”,
async : false,
success : function(data) {
//alert(“success 返回值:”+data.id);
if (data.id==1){
$(‘#mygrid’).datagrid(‘deleteRow’,rowIndex);
// alert(“删除成功”);
}
else
{
alert(“删除失败.”);
}
// 要提交的表单
},
error : function() {
alert(“删除出错.”);
}
});
}
//
}else{
alert(“请先选中数据行.”);
}
}
});
}
function saveData(){
if ($(‘#fm’).form(“validate”)){
var bh= $(“#bh”).val();
var mc= $(“#mc”).val();
var bz=$(“#bz”).val();
var obj={};
obj.bh=bh;
obj.mc=mc;
obj.bz=bz;
var msgdata=$.toJSON(obj) ;
//alert(msgdata);
if ((bh==0) ){
alert(“请先刷新数据再进行修改.”);
}
else{
if ((bh==-1) ){
//alert(“新增 bh=”+row.bh);
$.ajax({
url : “../../../jersey/sjzx/skfs/appendData?ywid=001”,
type : “POST”,
data:msgdata,
dataType : “json”,
contentType : “application/json;charset=utf-8”,
async : false,
success : function(data) {
if(data.id==1){
// row.bh=data.other;
//$(“#bh”).val(data.other);
$(‘#dlg’).dialog(‘close’);
dataGridReload();
}else{
alert(“新增失败”);
}
},
error : function() {
alert(“新增出错”);
}
});
}
else{
//alert(“修改 id=”+row.bh);
$.ajax({
url : “../../../jersey/sjzx/skfs/updateData?ywid=001”,
type : “POST”,
data:msgdata,
dataType : “json”,
contentType : “application/json;charset=utf-8”,
async : false,
success : function(data) {
if (data.id==1){
$(‘#dlg’).dialog(‘close’);
dataGridReload();
}else{
alert(“修改失败”);
}
// 要提交的表单
},
error : function() {
alert(“修改出错”);
}
});
}
}
}
}
5.2 html
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<meta name=”keywords” content=”jquery,ui,easy,easyui,web”>
<meta name=”description”
content=”easyui help you build your web page easily!”>
<title>类别</title>
<link rel=”stylesheet” type=”text/css” href=”../../../js/easyui/themes/default/easyui.css”>
<link rel=”stylesheet” type=”text/css” href=”../../../js/easyui/themes/icon.css”>
<link rel=”stylesheet” type=”text/css” href=”../../../js/easyui/demoli.css”>
<script type=”text/javascript” src=”../../../js/jquery.min.js”></script>
<script type=”text/javascript” src=”../../../js/jquery.json.min.js”></script>
<script type=”text/javascript” src=”../../../js/easyui/jquery.easyui.min.js”></script>
<script type=”text/javascript” src=”../../../js/easyui/locale/easyui-lang-zh_CN.js”></script>
<script type=”text/javascript” src=”skfsForm.js”></script>
<style type=”text/css”>
#fm
{
margin: 0;
padding: 10px 30px;
}
.ftitle
{
font-size: 14px;
font-weight: bold;
padding: 5px 0;
margin-bottom: 10px;
border-bottom: 1px solid #ccc;
}
.fitem
{
margin-bottom: 5px;
}
.fitem label
{
display: inline-block;
width: 80px;
}
</style>
</head>
<body>
<div id=”tb” style=”height:auto”>
<a href=”javascript:void(0)” class=”easyui-linkbutton” data-options=”iconCls:’icon-add’,plain:true” οnclick=”appendRowTools()”>新增</a>
<a href=”javascript:void(0)” class=”easyui-linkbutton” data-options=”iconCls:’icon-edit’,plain:true” οnclick=”editRowTools()”>修改</a>
<a href=”javascript:void(0)” class=”easyui-linkbutton” data-options=”iconCls:’icon-remove’,plain:true” οnclick=”deleteRowTools()”>删除</a>
<a href=”javascript:void(0)” class=”easyui-linkbutton” data-options=”iconCls:’icon-reload’,plain:true” οnclick=”dataGridReload()”>刷新</a>
    查询条件 
编号:<input id=”cxbh” class=”easyui-textbox” data-options=”prompt:’输入编号'” style=”width:80px,height:32px”>
名称:<input id=”cxmc” class=”easyui-textbox” data-options=”prompt:’输入名称'” style=”width:80px,height:32px”>
<a href=”javascript:void(0)” class=”easyui-linkbutton” data-options=”iconCls:’icon-search’,plain:true” οnclick=”getDataByTj()”>查询</a>
</div>
<table id=”mygrid” >
</table>
<div id=”dlg” class=”easyui-dialog” style=”width: 400px; height: 300px; padding: 10px 20px;”
closed=”true” buttons=”#dlg-buttons”>
<div class=”ftitle”>
信息编辑
</div>
<form id=”fm” method=”post”>
<div class=”fitem”>
<label for=”bh”>编号</label>
<input id=”bh” name=”bh” readonly=”true” />
</div>
<div class=”fitem”>
<label>
名称</label>
<input id=”mc” name=”mc” class=”easyui-validatebox” required=”true” />
</div>
<div class=”fitem”>
<label>
编码</label>
<input id=”bm” name=”bm” class=”easyui-validatebox” />
</div>
<div class=”fitem”>
<label>
备注</label>
<input id=”bz” name=”bz” class=”easyui-validatebox” />
</div>
<input type=”hidden” name=”action” id=”hidtype” />
<input type=”hidden” name=”ID” id=”Nameid” />
</form>
</div>
<div id=”dlg-buttons”>
<a href=”javascript:void(0)” class=”easyui-linkbutton” οnclick=”saveData()” iconcls=”icon-save”>保存</a>
<a href=”javascript:void(0)” class=”easyui-linkbutton” οnclick=”javascript:$(‘#dlg’).dialog(‘close’)”
iconcls=”icon-cancel”>取消</a>
</div>
</body>
</html>
今天的文章spring boot+mybatis增删改查_java增删改查功能怎么实现分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/87999.html