基于JdbcTemplate 的动态数据,增删改查功能实现

Posted 洛阳泰山

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于JdbcTemplate 的动态数据,增删改查功能实现相关的知识,希望对你有一定的参考价值。

核心代码如下


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.gis.common.constant.AppConst;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class DbDatabaseService 

    @Resource
    private  JdbcTemplate jdbcTemplate;

    public List<String> queryColumns(Long id) 
        return queryColumns(AppConst.TABLE_PREFIX+ id);
    

    public List<Map<String, Object>> queryClazz(Long id, Map<String, Object> params) 
        return list(AppConst.TABLE_PREFIX+ id, null, params);
    

    public List<Map<String, Object>> queryClazz(Long id, Set<String> columns, Map<String, Object> params) 
        return list(AppConst.TABLE_PREFIX+ id, columns, params);
    

    public Integer count(Long id, Map<String, Object> params) 
        return count(AppConst.TABLE_PREFIX+ id, params);
    

    public Boolean insert(Long id, Map<String, Object> map) 
        int flag = insert(AppConst.TABLE_PREFIX+ id, map);
        return flag > 0;
    

    public Boolean insertBatch(Long id,List<Map<String,Object>> list)
        Boolean boo=true;
        int[] flags=insertBatch(AppConst.TABLE_PREFIX+id,list);
        for (int i = 0; i < flags.length; i++) 
            int flag = flags[i];
            if(flag<1)
                boo=false;
            
        
        return boo;
    



    public Boolean  update(Long id,Map<String,Object> map)
        int flag=update(AppConst.TABLE_PREFIX+id,map);
        if(flag>0)
            return true;
        
        return false;
    

    private List<String> queryColumns(String tableName)
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE table_schema=\\'public\\' AND TABLE_NAME=\\'"+tableName+"\\' ");
        return jdbcTemplate.queryForList(sb.toString(),String.class);
    

    public Integer count(String tableName,Map<String,Object> params)
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT COUNT(*) FROM \\"public\\".\\""+tableName+"\\" ");
        filterMap(tableName,params);
        sb.append(getParamsSql(params));
        return jdbcTemplate.queryForObject(sb.toString(), Integer.class);
    

    public List<Map<String, Object>> list(String tableName,Map<String, Object> params) 
        return list(tableName,null,params);
    

    public List<Map<String, Object>> list(String tableName, Set<String> columns, Map<String, Object> params) 
        StringBuffer sb = new StringBuffer();
        if (CollectionUtils.isNotEmpty(columns)) 
            String columnSql = StringUtils.join(columns, ",");
            sb.append("SELECT " + columnSql + " FROM \\"public\\".\\"" + tableName + "\\" ");
         else 
            sb.append("SELECT * FROM \\"public\\".\\"" + tableName + "\\" ");
        
        filterMap(tableName, params);
        sb.append(getParamsSql(params));
        return jdbcTemplate.queryForList(sb.toString());
    

    private String getParamsSql(Map<String,Object> params)
        if(params==null||params.size()==0)
            return "";
        
        StringBuffer bf = new StringBuffer();
        if(params!=null)
            bf.append(" WHERE ");
            params.forEach((k,v)->
                if(v instanceof String)
                    v=((String) v).replace("&lt;","<");
                    v=((String) v).replace("&gt;",">");
                
                bf.append(k+v+" AND ");
            );
            int index=bf.lastIndexOf("AND");
            if(index!=-1)
                bf.delete(index,index+3);
            
            bf.append(bf);
            Object sortObj=params.get("sortField");
            Object orderObj=params.get("order");
            if(sortObj!=null && orderObj!=null)
                String  sortField= (String)sortObj;
                if(StringUtil.isNotBlank(sortField))
                    bf.append(" order by "+sortField);
                
                Boolean  order= (Boolean)orderObj;
                if(order)
                    bf.append(" asc");
                else 
                    bf.append(" desc");
                
            
        
        return bf.toString();
    

    public int insert(String tableName, Map<String,Object> map)
        return jdbcTemplate.update(insertSql(tableName,map),map.values().toArray());
    

    private Map<String,Object> filterMap(String tableName, Map<String,Object> map)
        List<String> columns= queryColumns(tableName);
        if(map!=null && map.size()!=0)
            Set<String> keys=map.keySet();
            for (String key : keys) 
                if(!columns.contains(key))
                    map.remove(key);
                
            
        
        return map;
    

    private String insertSql(String tableName, Map<String,Object> map)
        StringBuffer sb = new StringBuffer();
        filterMap(tableName,map);
        sb.append("INSERT INTO \\"public\\".\\""+tableName+"\\" (");
        map.forEach((k,v)-> sb.append(k+","););
        sb.append(") VALUES (");
        map.forEach((k,v)->
            sb.append("?,");
        );
        sb.append("); \\n");
        return sb.toString().replace(",)",")");
    


    public int[] insertBatch(String tableName, List<Map<String,Object>> list)
        List<Object[]> batchArgs=new ArrayList<Object[]>();
        String sql=insertSql(tableName,list.get(0));
        list.forEach(e->
            batchArgs.add(e.values().toArray());
        );
        return jdbcTemplate.batchUpdate(sql,batchArgs);
    

    private int update(String tableName, Map<String,Object> map)
        StringBuffer sb = new StringBuffer();
        sb.append("UPDATE  \\"public\\".\\""+tableName+"\\" SET  ");
        filterMap(tableName,map);
        List<Object> args=new ArrayList<>();
        map.forEach((k,v)->
            if(!"id".equals(k))
                sb.append(k+"=?,");
                args.add(v);
            
        );
        int index=sb.lastIndexOf(",");
        sb.delete(index,index+1);
        sb.append(" WHERE id=?");
        args.add(map.get("id"));
        return jdbcTemplate.update(sb.toString(),args);
    

    private String deleteSql(String tableName,List<Long> ids)
        StringBuffer sb = new StringBuffer();
            sb.append("DELETE FROM  \\"public\\".\\""+tableName+"\\"  WHERE id IN (");
            ids.forEach(id->
                sb.append("?,");
            );
            sb.append("); \\n");
            String sql= sb.toString().replace(",);",");");
            return sql;
    

    public Boolean  deleteBatch(Long id,List<Long> ids)
        return deleteBatch(AppConst.TABLE_PREFIX+id,ids);
    

    private int delete(String tableName,List<Long> ids)
        String sql=deleteSql(tableName,ids);
        return jdbcTemplate.update(sql,ids);
    


    private Boolean deleteBatch(String tableName,List<Long> ids)
        Boolean boo=true;
        if (ids.size() > 999) 
            for (int i = 0; i < ids.size(); i += 999) 
                int lastIndex = Math.min(i + 999, ids.size());
                int flag= delete(tableName,ids.subList(i, lastIndex));
                if(flag<1)
                   boo=false;
               
            
        else 
            int flag= delete(tableName,ids);
            if(flag<1)
                boo=false;
            
        
        return boo;
    



以上是关于基于JdbcTemplate 的动态数据,增删改查功能实现的主要内容,如果未能解决你的问题,请参考以下文章

JdbcTemplate(增删改查以及以注释实现增删改查)

spring学习spring的jdbcTemplate(增删改查封装)

使用JdbcTemplate操作数据库(增删改查)。具体代码+讲解 上篇

java--使用jdbcTemplate进行增删改查

基于mybatis的动态表数据增删改查方法实现

基于mybatis的动态表数据增删改查方法实现