UAP具体实现增删改查的方法

       UAP中对表单的保存、增删改查以及自定义的分页查询方法如下:

1.创建controller类,对表单值的获取和对数据库的保存。具体代码如下:

package com.sgcc.module1.pm_001;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import *****


@Controller
@RequestMapping("/test_controller1")
public class TestController1 {

@Resource
private HttpMessageConverter coverter;
    
// 获取明细信息,获取某条记录
@RequestMapping("/{id}")
public @ItemResponseBody
QueryResultObject get(@PathVariable String id) {


IHibernateDao hibernateDao = (IHibernateDao) ComponentFactory
.getBean("hibernateDao");// 获取hibernateDao
//Object bizc = ComponentFactory.getBean("temployeeBizc");// 获取某一bizc


java.util.Map ooj;
if ("null".equals(id)) {
ooj = null;
} else {
// select 字段 要与 js 中 formEntityContainer 的字段name属性一致,主键一定要包括在内
ooj = hibernateDao
.queryForMapWithSql(
"select user_id,brief,about,pswd,birthday,gender,nation,hobby from pub_users where user_id=?",
new Object[] { id });
}


QueryResultObject qObject = new QueryResultObject();
List items = new ArrayList();
items.add(ooj);
qObject.setItems(items);


return qObject.addDicItems(wrapDictList());
}


// 保存数据方法定义
@RequestMapping(value = "/save", method = RequestMethod.POST)
public @ItemResponseBody
List save(HttpServletRequest request) {


IHibernateDao hibernateDao = (IHibernateDao) ComponentFactory
.getBean("hibernateDao");// 获取hibernateDao


try {
// 获取servlet API
ServletServerHttpRequest servlet = new BodyReaderRequestWrapper(
request);
// 将模型转换为java对象
java.util.Map[] formData = coverter.converter(new java.util.Map[0],
servlet);
List voList = new ArrayList();


             String primaryKey="user_id";
// 遍历表单数据, 如果当前数据在数据库里存在, 则做修改, 否则做新增处理
for (int i = 0; i < formData.length; i++) {
java.util.Map dataObj = formData[i]; 
Object primaryKeyValue = dataObj.get(primaryKey);
 
int isExsit = hibernateDao.queryForIntWithSql(
"select count(*) from pub_users where user_id=?",
new Object[] { primaryKeyValue });
if (isExsit > 0) {
// 更新 
Object[] instr=updateObjStr(dataObj,primaryKey);
String sql = "update  pub_users  set "+instr[0]+" where user_id='"+primaryKeyValue+"'";
hibernateDao.executeSqlUpdate(sql, (Object[])instr[1]);
} else {
// 新增 
Object[] instr=insertObjStr(dataObj);
String sql = "insert into pub_users (user_id, "+instr[0]+" ) values('"+java.util.UUID.randomUUID().toString().replaceAll("-", "")+"',"+instr[1]+")";
hibernateDao.executeSqlUpdate(sql, (Object[])instr[2]);
}


voList.add(dataObj);


}
return voList;
} catch (ServiceValidatorBaseException e) {
throw e;
} catch (Exception e) {
throw new RestClientException("保存方法异常", e);
}
}


// 删除数据
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public @VoidResponseBody
Object delete(@IdRequestBody IDRequestObject idObject) {
String[] ids = idObject.getIds();

IHibernateDao hibernateDao = (IHibernateDao) ComponentFactory
.getBean("hibernateDao"); // 获取hibernateDao,注意这里必须获取hibernateDao,否则无法对数据库进行操作

for (String id : ids) {
String sql = "delete from pub_users where user_id=?";
hibernateDao.executeSqlUpdate(sql, new Object[]{id});
}
return null;
}
    
//集合类型字段数据获取
private List wrapDictList() {


IHibernateDao hibernateDao = (IHibernateDao) ComponentFactory
.getBean("hibernateDao");
List dicts = new ArrayList();
DicItems dictPub_usersGender = new DicItems();
dictPub_usersGender.setName("gender");
dictPub_usersGender
.setValues(hibernateDao
.queryForListWithSql("select dic_key value,dic_value text from dic_data where dic_type='gender' "));
DicItems dictPub_usersNation = new DicItems();
dictPub_usersNation.setName("nation");
dictPub_usersNation
.setValues(hibernateDao
.queryForListWithSql("select dic_key value,dic_value text from dic_data where dic_type='nation' "));
DicItems dictPub_usersHobby = new DicItems();
dictPub_usersHobby.setName("hobby");
dictPub_usersHobby
.setValues(hibernateDao
.queryForListWithSql("select dic_key value,dic_value text from dic_data where dic_type='hobby' "));
dicts.add(dictPub_usersGender);
dicts.add(dictPub_usersNation);
dicts.add(dictPub_usersHobby);
return dicts;
}

//列表查询
@RequestMapping("/")
    public @ItemResponseBody QueryResultObject query(@QueryRequestParam("params") RequestCondition queryCondition){

IHibernateDao hibernateDao = (IHibernateDao) ComponentFactory
.getBean("hibernateDao");


QueryResultObject qo = new QueryResultObject();


try {
 


String sql = " select user_id,brief,about,pswd,birthday,gender,nation,hobby from pub_users  ";


 
String defaultSorter = " birthday asc";
            HashMap operMap=new HashMap();
            //mysql like     concat('%',?,'%')
            //sqlserver      '%'+?+'%'
            //oracle         '%'||'%'
            //postgresql     '%'||'%'
            
            //operMap.put("name556", "name like concat('%',?,'%') ");
            
            
Object[] b_condtions = QueryUtil
.formatPagingSql_conditions(QueryUtil
.FilterToConidtions(queryCondition.getFilter(),operMap));


Object[] b_sql = QueryUtil.formatPagingSql_sql(sql,null);


SqlInfo info = QueryUtil.formatPagingSql(
b_sql,
b_condtions,
queryCondition.getSorter() != null ? queryCondition
.getSorter() : defaultSorter);

System.out.println("====>> " + info.sql);
 
SplitResult rs = QueryUtil.sqlResult(info.sql, info.sqlParas,
hibernateDao,
Integer.valueOf(queryCondition.getPageIndex()),
Integer.valueOf(queryCondition.getPageSize()));
 
qo.setItemCount(rs.getCount());
qo.setItems(rs.getReulst());


} catch (Throwable ex) {
}


return qo.addDicItems(wrapDictList());


  
    }





//内置通用方法:sql拼接
public Object[] insertObjStr(java.util.Map map) {


StringBuffer outStr1 = new StringBuffer();
StringBuffer outStr2 = new StringBuffer();
Object[] outPara3 = new Object[map.keySet().size() - 1];
java.util.Set key = map.keySet();
int i = 0;
for (Object kobj : key) {
if (!kobj.toString().equals("mxVirtualId")) {


if (outStr1.length() > 0) {
outStr1.append(",");
}
if (outStr2.length() > 0) {
outStr2.append(",");

outStr1.append(kobj);
outStr2.append("?");


outPara3[i] = map.get(kobj);
i++;
}
}


return new Object[]{outStr1,outStr2,outPara3};
}
//内置通用方法:sql拼接,自定义sql功能
public Object[] updateObjStr(java.util.Map map,String primaryKey) {
StringBuffer outStr1 = new StringBuffer(); 
Object[] outPara3 = new Object[map.keySet().size() - 1];
java.util.Set key = map.keySet();
int i = 0;
for (Object kobj : key) {
if (!kobj.toString().equals(primaryKey)) {


if (outStr1.length() > 0) {
outStr1.append(",");
}
 
outStr1.append(kobj+"=?"); 
outPara3[i] = map.get(kobj);
i++;
}
}
return new Object[]{outStr1,outPara3};
}
}

你可能感兴趣的:(UAP学习总结)