自定义orm,快速完成增删改查

自定义orm


父类

package com.tlzn.tkwl.usercenter.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tlzn.tkwl.entity.result.CommonResult;
import com.tlzn.tkwl.entity.result.saveorupdate.RowCheck;
import com.tlzn.tkwl.entity.result.saveorupdate.SaveOrUpdateResult;

import com.tlzn.tkwl.util.RedisUtil;
import com.tlzn.tkwl.util.StringUtil;
import com.tlzn.tkwl.util.ReflectUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.*;

public abstract class BaseService {


    ObjectMapper objectMapper = new ObjectMapper();

    protected abstract RowCheck getRowCheckResult(Object object);
    protected abstract List<String> getLogicIdFieldList();


    public static final String CURDURL = "http://curd-service/";
    /**
     * 添加
     * @param module
     * @param datasouce
     * @param type
     * @param jsonData
     * @return
     * @throws Exception
     */
    protected String save( RestTemplate restTemplate,String module,String datasouce,String pass,String addr,Integer port,Class<?> type,String jsonData) throws Exception{
        Object object = objectMapper.readValue(jsonData, type);
        SaveOrUpdateResult saveOrUpdateResult = new SaveOrUpdateResult();
        RowCheck rowCheck = getRowCheckResult(object);
        if(rowCheck.getColumnMessageMap().size() > 0){
            rowCheck.setCheck(false);
            saveOrUpdateResult.setRowCheck(rowCheck);
            return objectMapper.writeValueAsString(saveOrUpdateResult);
        }

        String sql = "SELECT COUNT(1) as count  FROM " + type.getSimpleName() + " WHERE ";
        List<String> logicIdFieldList = getLogicIdFieldList();
        for(int i=0;i<logicIdFieldList.size();i++){
            String field = logicIdFieldList.get(i);
            if(i==0)
                sql += field +  " = ? ";
            else
                sql += " and "+field +  " = ? ";
        }
        Map<String,String> dataMap = new LinkedHashMap<>();

        for(int i=0;i<logicIdFieldList.size();i++) {
            Object value =  ReflectUtil.getFieldValue(object,logicIdFieldList.get(i));
            String name =object.getClass().getDeclaredField(logicIdFieldList.get(i)).getType().getName();
            Object types  =  name.substring(name.lastIndexOf(".")+1);;  //获取字段类型
            dataMap.put(i+"_"+types,String.valueOf(value));
        }

        String url = CURDURL+"/curd/ijsondata/selectBySql?module="+module+"&datasource="+datasouce+"&sql="+sql+"&jsonData="+ URLEncoder.encode(objectMapper.writeValueAsString(dataMap),"utf-8");
        ResponseEntity<CommonResult> responseEntity =  restTemplate.getForEntity(url,CommonResult.class);
        CommonResult commonResult = responseEntity.getBody();
        List<Map> results = new ArrayList<>();
        if (commonResult.getData() instanceof ArrayList<?>) {
            for (Object o : (List<?>) commonResult.getData()) {
                results.add(Map.class.cast(o));
            }
            results.get(0).get("count");
        }
        if((int)results.get(0).get("count")> 0){
            rowCheck.getRowMessageList().add("逻辑主键重复");
            rowCheck.setCheck(false);
            saveOrUpdateResult.setRowCheck(rowCheck);
            return objectMapper.writeValueAsString(saveOrUpdateResult);
        }

//        String insertSql = RedisUtil.getTable_Insert(addr,port,pass,type);
//        System.out.println(insertSql);
//        Map<String,String> insertMap =  RedisUtil.getSqlParamMap(addr,port,pass,object);


        String insertSql = "INSERT INTO `tkwl_usercenter`.`usercenter_user`(`db_id`, `db_mobilePhone`, `db_password`, `db_id_username`) VALUES (?,?,?,?);";
        Map<String,String> insertMap = new LinkedHashMap<>();
        insertMap.put("0_String",ReflectUtil.getStringFieldValue(object,"db_id"));
        insertMap.put("1_String",ReflectUtil.getStringFieldValue(object,"db_mobilePhone"));
        insertMap.put("2_String",ReflectUtil.getStringFieldValue(object,"db_password"));
        insertMap.put("3_String",ReflectUtil.getStringFieldValue(object,"db_id_username"));


        String inserturl = CURDURL+"/curd/ijsondata/updateSql?module="+module+"&datasource="+datasouce+"&sql="+insertSql+"&jsonData="+
                                                                    URLEncoder.encode(objectMapper.writeValueAsString(insertMap),"utf-8");
        ResponseEntity<CommonResult> cresponseEntity =  restTemplate.getForEntity(inserturl,CommonResult.class);
        CommonResult cResult = cresponseEntity.getBody();
        if(cResult.isSuccess()){
            RedisUtil.setTableData(addr,port,pass,object);
            return objectMapper.writeValueAsString(saveOrUpdateResult);
        }
        else{
            saveOrUpdateResult.setSuccess(false);
            saveOrUpdateResult.setMessage(commonResult.getMessage());
            return objectMapper.writeValueAsString(saveOrUpdateResult);
        }
    }

    /**
     * 修改
     * @param module
     * @param datasouce
     * @param type
     * @param jsonData
     * @return
     * @throws Exception
     */
    protected String updateById( RestTemplate restTemplate,String module,String datasouce,String pass,String addr,Integer port,Class<?> type,String jsonData) throws Exception{
        Object object = objectMapper.readValue(jsonData, type);
        SaveOrUpdateResult saveOrUpdateResult = new SaveOrUpdateResult();
        RowCheck rowCheck = getRowCheckResult(object);
        if(rowCheck.getColumnMessageMap().size() > 0){
            rowCheck.setCheck(false);
            saveOrUpdateResult.setRowCheck(rowCheck);
            return objectMapper.writeValueAsString(saveOrUpdateResult);
        }
        String sql = "SELECT COUNT(1) as count  FROM " + type.getSimpleName() + " WHERE ";
        List<String> logicIdFieldList = getLogicIdFieldList();
        for(int i=0;i<logicIdFieldList.size();i++){
            String field = logicIdFieldList.get(i);
            if(i==0)
                sql += field +  " = ? ";
            else
                sql += " and "+field +  " = ? ";
        }
        Map<String,String> dataMap = new LinkedHashMap<>();

        for(int i=0;i<logicIdFieldList.size();i++) {
            Object value =  ReflectUtil.getFieldValue(object,logicIdFieldList.get(i));
            String name =object.getClass().getDeclaredField(logicIdFieldList.get(i)).getType().getName();
            Object types  =  name.substring(name.lastIndexOf(".")+1);;  //获取字段类型
            dataMap.put(i+"_"+types,String.valueOf(value));
        }

        String url = CURDURL+"/curd/ijsondata/selectBySql?module="+module+"&datasource="+datasouce+"&sql="+sql+
                "&jsonData="+ URLEncoder.encode(objectMapper.writeValueAsString(dataMap),"utf-8");
        ResponseEntity<CommonResult> responseEntity =  restTemplate.getForEntity(url,CommonResult.class);
        CommonResult commonResult = responseEntity.getBody();
        List<Map> results = new ArrayList<>();
        if (commonResult.getData() instanceof ArrayList<?>) {
            for (Object o : (List<?>) commonResult.getData()) {
                results.add(Map.class.cast(o));
            }
            results.get(0).get("count");
        }
        if((int)results.get(0).get("count")> 1){
            rowCheck.getRowMessageList().add("逻辑主键重复");
            rowCheck.setCheck(false);
            saveOrUpdateResult.setRowCheck(rowCheck);
            return objectMapper.writeValueAsString(saveOrUpdateResult);
        }


//        String updSql = RedisUtil.getTable_Update(addr,port,pass,type);
//        Map<String,String> updateMap = RedisUtil.getSqlParamMap(addr,port,pass,object);
        String updSql = "UPDATE usercenter_user SET db_mobilePhone = ?, db_id_username = ? WHERE db_id = ?";
        Map<String,String> updateMap = new LinkedHashMap<>();

        updateMap.put("0_String",ReflectUtil.getStringFieldValue(object,"db_mobilePhone"));
        updateMap.put("1_String",ReflectUtil.getStringFieldValue(object,"db_id_username"));
        updateMap.put("2_String",ReflectUtil.getStringFieldValue(object,"db_id"));


        String updurl = CURDURL+"/curd/ijsondata/updateSql?module="+module+"&datasource="+datasouce+"&sql="+updSql+"&jsonData="+
                URLEncoder.encode(objectMapper.writeValueAsString(updateMap),"utf-8");
        ResponseEntity<CommonResult> cresponseEntity =  restTemplate.getForEntity(updurl,CommonResult.class);
        CommonResult cResult = cresponseEntity.getBody();
        if(cResult.isSuccess()){
            RedisUtil.setTableData(addr,port,pass,object);
            return objectMapper.writeValueAsString(saveOrUpdateResult);
        }
        else{
            saveOrUpdateResult.setSuccess(false);
            saveOrUpdateResult.setMessage(commonResult.getMessage());
            return objectMapper.writeValueAsString(saveOrUpdateResult);
        }
    }


    /**
     * 删除
     * @param module
     * @param datasouce
     * @param jsonData
     * @return
     * @throws Exception
     */
    protected String deleteById( RestTemplate restTemplate,String module,String datasouce,String pass,String addr,Integer port,Class<?> type,String jsonData) throws Exception{

        SaveOrUpdateResult saveOrUpdateResult = new SaveOrUpdateResult();
        if(StringUtil.isEmpty(jsonData)){
            RowCheck rowCheck = new RowCheck();
            rowCheck.setCheck(false);
            saveOrUpdateResult.setRowCheck(rowCheck);
            rowCheck.getColumnMessageMap().put("db_id","id不能为空");
            return objectMapper.writeValueAsString(saveOrUpdateResult);
        }
        String delsql = "DELETE FROM " + type.getSimpleName() + " WHERE db_id = ? " ;
        Map<String,String> dataMap = new LinkedHashMap<>();
        dataMap.put("0_String",jsonData);


        String url = CURDURL+"/curd/ijsondata/updateSql?module="+module+"&datasource="+datasouce+"&sql="+delsql+"&jsonData="+ URLEncoder.encode(objectMapper.writeValueAsString(dataMap),"utf-8");
        ResponseEntity<CommonResult> responseEntity =  restTemplate.getForEntity(url,CommonResult.class);
        CommonResult commonResult = responseEntity.getBody();
        if(commonResult.isSuccess()){
            RedisUtil.delTableData(addr,port,pass,type,jsonData);
            return objectMapper.writeValueAsString(saveOrUpdateResult);
        }else{
            saveOrUpdateResult.setSuccess(false);
            saveOrUpdateResult.setMessage(commonResult.getMessage());
            return objectMapper.writeValueAsString(saveOrUpdateResult);
        }

    }

    /**
     * 查看一条详情
     * @param module
     * @param datasouce
     * @param jsonData
     * @return
     * @throws Exception
     */
    protected String selectById( RestTemplate restTemplate,String module,String datasouce,String pass,String addr,Integer port,Class<?> type,String jsonData) throws Exception{


        String sql = "SELECT * FROM " + type.getSimpleName() + " WHERE db_id = ? ";
        Map<String,String> dataMap = new LinkedHashMap<>();
        dataMap.put("0_String",jsonData);

        String url = CURDURL+"/curd/ijsondata/selectBySql?module="+module+"&datasource="+datasouce+"&sql="+sql+"&jsonData="+ URLEncoder.encode(objectMapper.writeValueAsString(dataMap),"utf-8");
        ResponseEntity<CommonResult> responseEntity =  restTemplate.getForEntity(url,CommonResult.class);
        CommonResult commonResult = responseEntity.getBody();

        if(commonResult.isSuccess()){
            return objectMapper.writeValueAsString(commonResult);
        }
        else{
            commonResult.setSuccess(false);
            commonResult.setMessage(commonResult.getMessage());
            return objectMapper.writeValueAsString(commonResult);
        }

    }

    /**
     * 删除多条
     * @param module
     * @param datasouce
     * @param jsonData
     * @return
     * @throws Exception
     */
    protected String deleteList( RestTemplate restTemplate,String module,String datasouce,String pass,String addr,Integer port,Class<?> type,String jsonData) throws Exception{


        String sql = "  delete  from  " + type.getSimpleName() + "  where  db_id    = ? " ;

        List<String> list= Arrays.asList(jsonData.split(","));
        List<Object[]>  sList = new LinkedList<>();
        for( String s:list){
            List<String >a = new LinkedList<>();
            a.add(s);
            sList.add(a.toArray());
        }

        JSONArray array= JSONArray.parseArray(JSON.toJSONString(sList));
        Map<String,Object> dataMap = new LinkedHashMap<>();
        dataMap.put("0_String",objectMapper.writeValueAsString(array));
        String url = CURDURL+"/curd/ijsondata/updateSql?module="+module+"&datasource="+datasouce+"&sql="+sql+"&jsonData="+
                                                    URLEncoder.encode(objectMapper.writeValueAsString(dataMap),"utf-8");
        ResponseEntity<CommonResult> responseEntity =  restTemplate.getForEntity(url,CommonResult.class);
        CommonResult commonResult = responseEntity.getBody();

        if(commonResult.isSuccess()){

            //删除多条
            RedisUtil.delMultiTableData(addr,port,pass,type,list);
            return objectMapper.writeValueAsString(commonResult);
        }
        else{
            commonResult.setSuccess(false);
            commonResult.setMessage(commonResult.getMessage());
            return objectMapper.writeValueAsString(commonResult);
        }
    }

    /**
     * 按条件查询所有
     * @param restTemplate
     * @param module
     * @param datasouce
     * @return
     * @throws Exception
     */
    protected String selectByCondition( RestTemplate restTemplate, String module, String datasouce, String pass,String addr,Integer port,Class<?> type, String jsonData) throws Exception{

        String sql = "SELECT * FROM " + type.getSimpleName() + "  where 1= 1 ";
        Map<String,Object> dataMap = new LinkedHashMap<>();


        if(!StringUtil.isEmpty(jsonData)){

            Object object = objectMapper.readValue(jsonData, type);
            Field[] feilds = object.getClass().getDeclaredFields();
            Integer ui_currentPage=0;
            Integer Ui_pageSize=0;
            for(Field field:feilds){
                field.setAccessible(true);
                String name  = field.getName();
                String types = field.getType().toString();
                String fieldtype = types.substring(types.lastIndexOf(".")+1);
                Object value = field.get(object);
                if(value!=null&&name.startsWith("db")){
                    sql+=" and "+name+" = ? ";
                    dataMap.put(dataMap.size()+"_"+fieldtype,value);
                }
                if("ui_currentPage".equals(value)){
                    ui_currentPage = Integer.valueOf((String) value);
                }
                if("Ui_pageSize".equals(value)){
                    Ui_pageSize = Integer.valueOf((String) value);
                }
            }
            if(ui_currentPage!=0&&Ui_pageSize!=0){
                sql+="  limit "+(ui_currentPage-1)*Ui_pageSize+" , "+Ui_pageSize;
            }

        }

        String url = CURDURL+"/curd/ijsondata/selectBySql?module="+module+"&datasource="+datasouce+"&sql="+sql+"&jsonData="+ URLEncoder.encode(objectMapper.writeValueAsString(dataMap),"utf-8");
        ResponseEntity<CommonResult> responseEntity =  restTemplate.getForEntity(url,CommonResult.class);
        CommonResult commonResult = responseEntity.getBody();
        if(commonResult.isSuccess()){
            return objectMapper.writeValueAsString(commonResult);
        }
        else{
            commonResult.setSuccess(false);
            commonResult.setMessage(commonResult.getMessage());
            return objectMapper.writeValueAsString(commonResult);
        }
    }


    /**
     * 查询count
     * @param restTemplate
     * @param module
     * @param datasouce

     * @return
     * @throws Exception
     */
    protected String selectCountByCondition(RestTemplate restTemplate,String module,String datasouce,String pass,String addr,Integer port,Class<?> type,String jsonData) throws Exception{

        String sql = "SELECT count(*) as count FROM  " + type.getSimpleName() + "  where 1= 1 ";
        Map<String,Object> dataMap = new LinkedHashMap<>();
        if(!StringUtil.isEmpty(jsonData)){
            //1 通过object获取实体类
            Object object = objectMapper.readValue(jsonData, type);
            //获取实体类中的对象数组,遍历数组获取参数进行判断是否为空,不为空的时候作为参数遍历到查询语句中
            Field[] feilds = object.getClass().getDeclaredFields();
            for(Field field:feilds){
                field.setAccessible(true);
                String name  = field.getName();
                String types = field.getType().toString();
                String fieldtype = types.substring(types.lastIndexOf(".")+1);
                Object value = field.get(object);
                if(value!=null&&name.startsWith("db")){
                    sql+=" and "+name+" = ? ";
                    dataMap.put(dataMap.size()+"_"+fieldtype,value);
                }
            }
        }
        String url = CURDURL+"/curd/ijsondata/selectBySql?module="+module+"&datasource="+datasouce+"&sql="+sql+"&jsonData="+ URLEncoder.encode(objectMapper.writeValueAsString(dataMap),"utf-8");
        ResponseEntity<CommonResult> responseEntity =  restTemplate.getForEntity(url,CommonResult.class);
        CommonResult commonResult = responseEntity.getBody();
        if(commonResult.isSuccess()){
            List<Map> results = new ArrayList<>();
            if (commonResult.getData() instanceof ArrayList<?>) {
                for (Object o : (List<?>) commonResult.getData()) {
                    results.add(Map.class.cast(o));
                }
                results.get(0).get("count");
            }
            commonResult.setData(results.get(0).get("count"));
            return objectMapper.writeValueAsString(commonResult);
        }
        else{
            commonResult.setSuccess(false);
            commonResult.setMessage(commonResult.getMessage());
            return objectMapper.writeValueAsString(commonResult);
        }

    }


}

子类

package com.tlzn.tkwl.usercenter.service;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.tlzn.tkwl.entity.result.CommonResult;
import com.tlzn.tkwl.entity.result.saveorupdate.RowCheck;
import com.tlzn.tkwl.entity.usercenter.Usercenter_User;
import com.tlzn.tkwl.interfaces.usercenter.IUserService;
import com.tlzn.tkwl.usercenter.context.UsercenterContext;
import com.tlzn.tkwl.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@RestController
@RequestMapping("/usercenter/iuser")
public class UserService extends BaseService implements IUserService {


    @Autowired
    RestTemplate restTemplate;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    UsercenterContext usercenterContext;


    ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping(value = "/getLoginUser")
    public String getLoginUser(String token) throws Exception {
        CommonResult commonResult = new CommonResult();
        return objectMapper.writeValueAsString(commonResult);
    }

    /**
     * @param object
     * @return
     */
    protected RowCheck getRowCheckResult(Object object) {

        RowCheck rowCheck = new RowCheck();
        Usercenter_User usercenter_User = (Usercenter_User)object;
        if(StringUtil.isEmpty(usercenter_User.getDb_id_username())){
            rowCheck.getColumnMessageMap().put("db_id_username","姓名不能为空");
        }
        if(StringUtil.isEmpty(usercenter_User.getDb_mobilePhone())){
            rowCheck.getColumnMessageMap().put("db_mobilePhone","手机号不能为空");
        }
        return rowCheck;
    }

    @Override
    protected List<String> getLogicIdFieldList() {
        ArrayList arrayList = new ArrayList();
        arrayList.add("db_mobilePhone");
        return arrayList;
    }


    @RequestMapping(value = "/save")
    public String save(@RequestParam(value="token") String token, @RequestParam(value="jsonData") String jsonData) throws Exception {
        return super.save(restTemplate,usercenterContext.getModule(),usercenterContext.getDatasouce(),usercenterContext.getRedisServerPass(),usercenterContext.getRedisServerAddr(),usercenterContext.getRedisServerPort(),Usercenter_User.class,jsonData);
    }


    @RequestMapping(value = "/updateById")
    public String updateById(@RequestParam(value="token") String token, @RequestParam(value="jsonData") String jsonData) throws Exception {
        return super.updateById(restTemplate,usercenterContext.getModule(),usercenterContext.getDatasouce(),usercenterContext.getRedisServerPass(),usercenterContext.getRedisServerAddr(),usercenterContext.getRedisServerPort(),Usercenter_User.class,jsonData);
    }


    @RequestMapping(value = "/deleteById")
    public String deleteById(String token, String id) throws Exception {
        return super.deleteById(restTemplate,usercenterContext.getModule(),usercenterContext.getDatasouce(),usercenterContext.getRedisServerPass(),usercenterContext.getRedisServerAddr(),usercenterContext.getRedisServerPort(),Usercenter_User.class,id);
    }

    @RequestMapping(value = "/selectById")
    public String selectById(String token, String id) throws Exception {
        return super.selectById(restTemplate,usercenterContext.getModule(),usercenterContext.getDatasouce(),usercenterContext.getRedisServerPass(),usercenterContext.getRedisServerAddr(),usercenterContext.getRedisServerPort(),Usercenter_User.class,id);
    }

    @RequestMapping(value = "/deleteList")
    public String deleteList(@RequestParam(value="token") String token, @RequestParam(value="idList")  String idList) throws Exception {
        return super.deleteList(restTemplate,usercenterContext.getModule(),usercenterContext.getDatasouce(),usercenterContext.getRedisServerPass(),usercenterContext.getRedisServerAddr(),usercenterContext.getRedisServerPort(),Usercenter_User.class,idList);
    }


    @RequestMapping(value = "/selectByCondition")
    public String selectByCondition(String token, @RequestParam(value="jsonData",required = false) String jsonData) throws Exception {
        return super.selectByCondition(restTemplate,usercenterContext.getModule(),usercenterContext.getDatasouce(),usercenterContext.getRedisServerPass(),usercenterContext.getRedisServerAddr(),usercenterContext.getRedisServerPort(),Usercenter_User.class,jsonData);
    }


    @RequestMapping(value = "/selectCountByCondition")
    public String selectCountByCondition(@RequestParam(value="token") String token, @RequestParam(value="jsonData",required = false) String jsonData) throws Exception {
        return super.selectCountByCondition(restTemplate,usercenterContext.getModule(),usercenterContext.getDatasouce(),usercenterContext.getRedisServerPass(),usercenterContext.getRedisServerAddr(),usercenterContext.getRedisServerPort(),Usercenter_User.class,jsonData);

    }

    public String updatePassword(String token, String jsonData) throws Exception {
        return null;
    }


}

配置类
package com.tlzn.tkwl.usercenter.config;


import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * RestTemplate配置模板
 *
 * @author like
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(ClientHttpRequestFactory simpleClientHttpRequestFactory) {
        return new RestTemplate(simpleClientHttpRequestFactory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        return factory;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值