cvsFeng
2015-11-11 19:55:26
Spring JdbcTemplete泛型封装类实现
package cn.com.commons.sql; import java.util.HashSet; import java.util.Set; /** * @author Administrator Feng * 条件值 */ public class BaseCondition <T>{ /**相当于and*/ private T and ; /**select为查找属性,默认为 '*' 查找所有*/ private Set<String> select; /**逐步替换预置select*/ private Set<String> selectParam ; /**模糊查找*/ private T like ; /**或*/ private T or ; /**分页*/ private BasePage page; public BasePage getPage() { return page; } /**分页*/ public void setPage(BasePage page) { this.page = page; } /**分组*/ private String group_by; /**范围(最大)*/ private T max; /**范围(最小)*/ private T min; public T getMax() { return max; } /**范围(最大)*/ public void setMax(T max) { this.max = max; } public T getMin() { return min; } /**范围(最小)*/ public void setMin(T min) { this.min = min; } public Set<String> getSelect() { return select; } /**select为查找属性,默认为 '*' 查找所有*/ public void setSelect(Set<String> select) { this.select = select; } public String getGroup_by() { return group_by; } /**分组*/ public void setGroup_by(String group_by) { this.group_by = group_by; } public T getOr() { return or; } /**或*/ public void setOr(T or) { this.or = or; } public T getAnd() { return and; } /**相当于and*/ public void setAnd(T and) { this.and = and; } public T getLike() { return like; } /**模糊查找*/ public void setLike(T like) { this.like = like; } public Set<String> getSelectParam() { return selectParam; } public void setSelectParam(String selectParam) { if(selectParam.length()>0&&selectParam!=null){ String[] tempArr = selectParam.replace("{","").replace("}","").replace("'", "").replace("\"", "").split(","); Set<String> tempSelect = new HashSet<String>(); for (String element: tempArr) { tempSelect.add(element); } this.selectParam = tempSelect; }else { this.selectParam=null; } } public static void main(String[] args) { } }
package cn.com.commons.sql; import java.util.List; public interface BaseCrud<T,D> { /** * @author Administrator Feng * 2015-10-14 * @param t 插入数据对象 * @return 返回值为成功插入成功受影响的行数 */ public int insert(T t) ; /** * @author Administrator Feng * 2015-10-14 * @param objList 批量插入对象的集合 * 批量插入:返回值为受影响的条数,objList不可为空 * @return 成功插入受影响的行数 */ public int[] insertBatch(List<T> objList) ; /** * 2015-10-15 * @param 删除满足条件的对象 * 删除一条数据 condition 为后条件 返回值为受影响的行数 * @return 删除数据数量 */ public int delete(T condition); /** * @author Administrator Feng * 2015-10-20 * @param value 占位符所在位置的值 * @param sql 外部sql * @return 删除数据数量 */ public int delete(Object[] value,String sql); /** * @author Administrator Feng * 2015-10-26 * 查询,condition为查询值 * @param condition 查询条件 * @param C 查询的表名 * @return 查询数量集合 */ public List<T> select(BaseCondition<T> condition,Class<T> table); /** * @author Administrator Feng * 2015-10-26 * @param condition 查询条件 * @param table 查询表名 * @param result:DTO类型 * @return 查询数量集合 */ public List<D> select(BaseCondition<T> condition,Class<T> table,Class<D> result); /** * @author Administrator Feng * 2015-10-15 * @param condition为查询条件 * @param c 查询表名 * @return 查出一条数据 */ public T selectSingle(T condition,Class<T> c); /** * @author Administrator Feng * 2015-10-20 * @param value 为占位符所在位置的值 * @param c 查询出返回对象的类型 * @param sql 外部sql * @return 查出数据对象 */ public T selectSingle(Object[] value,Class<T> c,String sql); /** * @author Administrator Feng * 2015-10-28 * @param baseCondition查询条件 * @param table 查询表名 * @param c 返回值类型 * @return 查出数据对象 */ public D selectSingle(BaseCondition<T> condition,Class<T> table,Class<D> c); /** * @author Administrator Feng * 2015-10-20 * @param condtion 查询条件 * @param c 查询表名 * @return 满足条件的条数 */ public int selectCount(T condition,Class<T> c); /** * @author Administrator Feng * 2015-10-15 * @param condition 查询条件 * @param c 返回值类型 * @return 查出数据集合 */ public List<T> selectForList(T condition,Class<T> c); /** * @author Administrator Feng * 2015-10-28 * @param condition 查询条件 * @param table 数据库表 * @param c 返回值对象类型 * @return 查出数据集合 */ public List<D> selectForList(BaseCondition<T> condition,Class<T> table,Class<D> c); /** * @author Administrator Feng * 2015-10-28 * @param param 占位符所在位置值 * @param c 返回值对象类型 * @param sql 外部sql文件 * @return 查询出满足条件对象集合 */ public List<T> selectForList(Object[]param,Class<T> c,String sql); /** * @author Administrator Feng * 2015-10-14 * @param setValue 设置更新值 * @param condition 更新条件 * @return 更新成功的条数 */ public int update(T setValue,T condition) ; /** * @author Administrator Feng * 2015-10-26 * @param setValue 设置更新值 * @param condition 更新条件 * @return 更新成功的条数 */ public int update(T setValue,BaseCondition<T> condition); /** * @author Administrator Feng * 2015-10-14 * @param objList 设置更新值 * @param 更新条件 * @return 更新成功的条数 */ public int[] updateBatch(List<T> objList,T condition); }
package cn.com.commons.sql; /** * @author Administrator Feng * 2015-10-29 * 分页 */ public class BasePage { /**起始*/ private Integer begin ; /**结束*/ private Integer end ; public Integer getBegin() { return begin; } public void setBegin(Integer begin) { this.begin = begin; } public Integer getEnd() { return end; } public void setEnd(Integer end) { this.end = end; } }
package cn.com.commons.sql; /** * @author Administrator Feng * 2015-10-14 * 条件选择 */ public enum JoinChoice { /**基础选择、预置*/ select , delete , update , insert , values , set , form , /**条件*/ where ,//相等 or ,//或 like ,//模糊 and ,//并列 group_by ,//分组 limit //分页 }
package cn.com.commons.sql.impl; import java.lang.reflect.Field; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper; import org.springframework.stereotype.Repository; import cn.com.commons.sql.BaseCondition; import cn.com.commons.sql.BaseCrud; import cn.com.commons.sql.JoinChoice; @Repository @Qualifier("baseCrud") public class BaseCrudImpl<T,D> implements BaseCrud<T,D>{ @Autowired private JdbcTemplate jdbcTemplate; private Logger logger = Logger.getLogger(this.getClass()); public int insert(T t) { if(t==null){ return 0 ; } Field[] fields = t.getClass().getDeclaredFields(); String sql = ""; String sqlField = "" ; String sqlValue = "("; try { for (Field field : fields) { field.setAccessible(true); if(field.get(t)!=null&&!field.get(t).equals("")){ sqlField += field.getName()+","; sqlValue += "'"+field.get(t)+"'"+","; } } sqlField = sqlField.substring(0,sqlField.length()-1); sqlValue = sqlValue.substring(0,sqlValue.length()-1); sql = "INSERT INTO "+t.getClass().getSimpleName()+ "\t"+"\n"+"\t\t"+"("+ sqlField+")"+"\n"+ "\t"+" VALUES "+"\n"+ "\t\t"+sqlValue+")"; logger.info("\n"+sql); return this.jdbcTemplate.update(sql) ; } catch (Exception e) { logger.info(e.getMessage()); return 0; } } public int[] insertBatch(List<T> objList) { if(objList.size()==0){ return null; } String[] sqlArr = new String[objList.size()]; for (int i = 0 ;i<objList.size();i++) { T t = objList.get(i); Field[] fields = t.getClass().getDeclaredFields(); String sql = ""; String sqlField = "" ; String sqlValue = "("; try { for (Field field : fields) { field.setAccessible(true); if(field.get(t)!=null&&!field.get(t).equals("")){ sqlField += field.getName()+","; sqlValue += "'"+field.get(t)+"'"+","; } } } catch (Exception e) { logger.info(e.getMessage()); } sqlField = sqlField.substring(0,sqlField.length()-1); sqlValue = sqlValue.substring(0,sqlValue.length()-1); sql = "INSERT INTO "+t.getClass().getSimpleName()+ "\t"+"\n"+"\t\t"+"("+ sqlField+")"+"\n"+ "\t"+" VALUES "+"\n"+ "\t\t"+sqlValue+")"; logger.info(sql); sqlArr[i]=sql; } for(int i = 0 ;i<sqlArr.length;i++){ logger.info("\n"+sqlArr[i]); } try { return this.jdbcTemplate.batchUpdate(sqlArr) ; } catch (Exception e) { logger.info(e.getMessage()); return null ; } } public int update(T setValue,T condition) { if(setValue==null||condition==null){ return 0 ; } Field[] valueFields = setValue.getClass().getDeclaredFields(); String sql = ""; String sqlValueTemp = "" ; String sqlCondition = "" ; try { for (Field field : valueFields) { field.setAccessible(true); if(field.get(setValue)!=null&&!field.get(setValue).equals("")){ sqlValueTemp += field.getName()+"="+"'"+field.get(setValue)+"'"+","; } } sqlValueTemp = sqlValueTemp.substring(0,sqlValueTemp.length()-1); Field[] conditionFields = condition.getClass().getDeclaredFields(); for (Field field : conditionFields) { field.setAccessible(true); if(field.get(condition)!=null&&!field.get(condition).equals("")){ sqlCondition += field.getName()+"="+"'"+field.get(condition)+"'"+" AND "; } } sqlCondition = sqlCondition.substring(0,sqlCondition.length()-4); sql = "UPDATE "+setValue.getClass().getSimpleName()+" SET"+ "\t"+"\n"+"\t\t"+ sqlValueTemp+"\n"+ "\t"+" WHERE "+"\n"+ "\t\t"+sqlCondition ; logger.info("\n"+sql); return this.jdbcTemplate.update(sql) ; } catch (Exception e) { logger.info(e.getMessage()); return 0 ; } } public int update(T setValue,BaseCondition<T> condition) { if(setValue==null||condition==null){ return 0 ; } Field[] valueFields = setValue.getClass().getDeclaredFields(); String sql = ""; String sqlValueTemp = "" ; //String sqlCondition = "" ; try { for (Field field : valueFields) { field.setAccessible(true); if(field.get(setValue)!=null&&!field.get(setValue).equals("")){ sqlValueTemp += field.getName()+"="+"'"+field.get(setValue)+"'"+","; } } sql = "UPDATE "+setValue.getClass().getSimpleName()+" SET"+ "\t"+"\n"+"\t\t"+ sqlValueTemp+"\n"+ "\t"+" WHERE "+ getSQL(condition) ; logger.info("\n"+sql); return this.jdbcTemplate.update(sql) ; } catch (Exception e) { logger.info(e.getMessage()); } return 0; } public int[] updateBatch(List<T> objList, T condition) { if(objList.size()==0||condition==null){ return null; } String [] sql = new String[objList.size()]; String sqlCondition = ""; String prefixName = " update "+condition.getClass().getSimpleName()+" set "; String tempValue = ""; Field[] conditionFields = condition.getClass().getDeclaredFields(); try { for (Field field : conditionFields) { field.setAccessible(true); if(field.get(condition)!=null&&!field.get(condition).equals("")){ sqlCondition += " where "+field.getName()+"="+"'"+field.get(condition)+"'"+" AND "; } } } catch (Exception e) { logger.info(e.getMessage()); } sqlCondition = sqlCondition.substring(0,sqlCondition.length()-4); try { for (int i =0;i<objList.size();i++) { T t = objList.get(i); Field[] valueFields = t.getClass().getDeclaredFields(); for (Field field : valueFields) { field.setAccessible(true); if(field.get(t)!=null&&!field.get(t).equals("")){ tempValue += field.getName()+"="+"'"+field.get(t)+"'"+","; } } tempValue = tempValue.substring(0,tempValue.length()-1); sql[i] = prefixName+tempValue +sqlCondition; tempValue=""; } for(int i =0 ;i<sql.length;i++){ logger.info("\n"+sql[i]); } return jdbcTemplate.batchUpdate(sql); } catch (Exception e) { logger.info(e.getMessage()); return null ; } } public T selectSingle(T condition,Class<T> c) { if(condition==null||c==null){ return null ; } Field[] fields = condition.getClass().getDeclaredFields(); String sql = ""; String sqlField = "" ; String sqlValue = ""; String conditionValue = ""; try { for (Field field : fields) { field.setAccessible(true); if(field.get(condition)!=null&&!field.get(condition).equals("")){ sqlField = field.getName()+"="; sqlValue = "'"+field.get(condition)+"'"+" AND "; conditionValue+= sqlField+sqlValue; } } conditionValue = conditionValue.substring(0,conditionValue.length()-4); sql ="select * from "+condition.getClass().getSimpleName()+"\n"+ " where "+"\n"+ "\t"+conditionValue; logger.info("\n"+sql); return this.jdbcTemplate.queryForObject(sql,ParameterizedBeanPropertyRowMapper.newInstance(c)); } catch (Exception e) { logger.info(e.getMessage()); return null ; } } public D selectSingle(BaseCondition<T> condition,Class<T> table,Class<D> c) { if(condition==null||c==null){ return null ; } String sql = ""; String selectValue = "" ; try { if(condition.getSelect()!=null&&condition.getSelect().size()>0){ Set<String> select = condition.getSelect(); for (String temp : select) { selectValue+=temp+","; } selectValue=selectValue.substring(0, selectValue.length()-1); }else { selectValue = "*" ; } sql ="select "+selectValue+" from "+table.getSimpleName()+"\n"+ " where "+"\t"+getSQL(condition); logger.info("\n"+sql); return this.jdbcTemplate.queryForObject(sql,ParameterizedBeanPropertyRowMapper.newInstance(c)); } catch (Exception e) { logger.info(e.getMessage()); return null ; } } public List<T> selectForList(T condition,Class<T> c) { if(condition==null||c==null){ return null ; } Field[] fields = condition.getClass().getDeclaredFields(); String sql = ""; String sqlField = "" ; String sqlValue = ""; String conditionValue = ""; try { for (Field field : fields) { field.setAccessible(true); if(field.get(condition)!=null&&!field.get(condition).equals("")){ sqlField = field.getName()+"="; sqlValue = "'"+field.get(condition)+"'"+" AND "; conditionValue+= sqlField+sqlValue; } } conditionValue = conditionValue.substring(0,conditionValue.length()-4); sql ="select * from "+condition.getClass().getSimpleName()+"\n"+ " where "+"\n"+ "\t"+conditionValue; logger.info("\n"+sql); return this.jdbcTemplate.query(sql, ParameterizedBeanPropertyRowMapper.newInstance(c)); } catch (Exception e) { logger.info(e.getMessage()); return null ; } } public List<D> selectForList(BaseCondition<T> condition,Class<T> table,Class<D> c) { if(condition==null||c==null){ return null ; } String sql = ""; String selectValue = "" ; try { if(condition.getSelect()!=null&&condition.getSelect().size()>0){ Set<String> select = condition.getSelect(); for (String temp : select) { selectValue+=temp+","; } selectValue=selectValue.substring(0, selectValue.length()-1); }else { selectValue = "*" ; } sql ="select "+selectValue+" from "+table.getSimpleName()+"\n"+ " where "+"\t"+getSQL(condition); logger.info("\n"+sql); return this.jdbcTemplate.query(sql,ParameterizedBeanPropertyRowMapper.newInstance(c)); } catch (Exception e) { logger.info(e.getMessage()); return null ; } } public int selectCount(T condition, Class<T> c) { if(condition==null||c==null){ return 0 ; } Field[] fields = condition.getClass().getDeclaredFields(); String sql = ""; String sqlField = "" ; String sqlValue = ""; String conditionValue = ""; try { for (Field field : fields) { field.setAccessible(true); if(field.get(condition)!=null&&!field.get(condition).equals("")){ sqlField = field.getName()+"="; sqlValue = "'"+field.get(condition)+"'"+" AND "; conditionValue+= sqlField+sqlValue; } } conditionValue = conditionValue.substring(0,conditionValue.length()-4); sql ="select count(*) from "+condition.getClass().getSimpleName()+"\n"+ " where "+"\n"+ "\t"+conditionValue; logger.info("\n"+sql); return this.jdbcTemplate.queryForInt(sql) ; } catch (Exception e) { logger.info(e.getMessage()); return 0 ; } } public T selectSingle(Object[] param, Class<T> c, String sql) { if(sql==null||sql.length()==0||sql.equals("")||param.length==0||c==null){ return null; } try { return jdbcTemplate.queryForObject(sql,ParameterizedBeanPropertyRowMapper.newInstance(c), param); } catch (Exception e) { logger.info(e.getMessage()); return null ; } } public List<T> select(BaseCondition<T> condition,Class<T> c) { String sql = ""; try { if(condition.getSelect()==null){ sql="select * from "+c.getSimpleName()+"\n where " +" "+getSQL(condition); logger.info("\n"+sql); }else { Set<String> select = condition.getSelect(); for (String temp : select) { sql+=temp+","; } sql="select \n\t"+sql.substring(0,sql.length()-1)+"\n"+"from "+ c.getSimpleName()+"\n"+"where "+" "+getSQL(condition); logger.info("\n"+sql); } return jdbcTemplate.query(sql, ParameterizedBeanPropertyRowMapper.newInstance(c)); } catch (Exception e) { logger.info(e.getMessage()); return null; } } public List<D> select(BaseCondition<T> condition,Class<T> c,Class<D> result) { String sql = ""; try { if(condition.getSelect()==null){ sql="select * from "+c.getSimpleName()+"\n where " +" "+getSQL(condition); logger.info("\n"+sql); }else { Set<String> select = condition.getSelect(); for (String temp : select) { sql+=temp+","; } sql="select \n\t"+sql.substring(0,sql.length()-1)+"\n"+"from "+ c.getSimpleName()+"\n"+"where "+" "+getSQL(condition); logger.info("\n"+sql); } return jdbcTemplate.query(sql, ParameterizedBeanPropertyRowMapper.newInstance(result)); } catch (Exception e) { logger.info(e.getMessage()); return null; } } public int delete(Object[] param, String sql) { if(param.length==0||param==null||sql.length()==0||sql==null||sql.equals("")){ logger.info("参数不可为空"); return 0 ; } try { logger.info("\n"+sql); return jdbcTemplate.update(sql, param); } catch (Exception e) { logger.info(e.getMessage()); return 0 ; } } public List<T> selectForList(Object[] param, Class<T> c,String sql) { if(param.length==0||param==null||sql.length()==0||sql==null||sql.equals("")){ logger.info("参数不可为空"); return null ; } try { return jdbcTemplate.query(sql, param, ParameterizedBeanPropertyRowMapper.newInstance(c)); } catch (Exception e) { logger.info(e.getMessage()); return null ; } } public int delete(T condition) { if(condition==null){ return 0 ; } Field[] fields = condition.getClass().getDeclaredFields(); String sql = ""; String sqlField = "" ; String sqlValue = ""; String conditionValue = ""; try { for (Field field : fields) { field.setAccessible(true); if(field.get(condition)!=null&&!field.get(condition).equals("")){ sqlField = field.getName()+"="; sqlValue = "'"+field.get(condition)+"'"+" AND "; conditionValue+= sqlField+sqlValue; } } conditionValue = conditionValue.substring(0,conditionValue.length()-4); sql ="delete from "+condition.getClass().getSimpleName()+"\n"+ " where "+"\n"+ "\t"+conditionValue; logger.info("\n"+sql); return this.jdbcTemplate.update(sql); } catch (Exception e) { logger.info(e.getMessage()); return 0 ; } } private String getSQL(BaseCondition<T> baseCondition) throws Exception { //T like = baseCondition.getLike(); String tempChange = ""; T temp = null ; if(baseCondition.getAnd()!=null){ temp = baseCondition.getAnd(); Field[] fields = temp.getClass().getDeclaredFields(); tempChange +="\n\t"+getTempChange(fields, temp,JoinChoice.and); }if (baseCondition.getOr()!=null) { temp = baseCondition.getOr(); Field[] fields = temp.getClass().getDeclaredFields(); if(tempChange.length()>0){ tempChange+="\n\t"+" "+JoinChoice.or+getTempChange(fields, temp,JoinChoice.or); }else { tempChange+="\n\t"+getTempChange(fields, temp,JoinChoice.or); } }if(baseCondition.getMax()!=null&&baseCondition.getMin()!=null){ temp = baseCondition.getMax(); Field[] max = temp.getClass().getDeclaredFields(); String maxValue = ""; String minValue = ""; for (Field maxTemp : max) { maxTemp.setAccessible(true); if(maxTemp.get(temp)!=null){ maxValue=maxTemp.getName()+">='"+maxTemp.get(temp)+"'"; } } temp = baseCondition.getMin(); Field[] min = temp.getClass().getDeclaredFields(); for (Field minTemp : min) { minTemp.setAccessible(true); if(minTemp.get(temp)!=null){ minValue=minTemp.getName()+"<='"+minTemp.get(temp)+"'"; } } if(tempChange.length()>0){ tempChange+="and "+"\n\t"+maxValue+" and " +minValue; }else{ tempChange+="\n\t"+maxValue+" and " +minValue; } }if(baseCondition.getLike()!=null){ temp = baseCondition.getLike(); Field[] likefields = temp.getClass().getDeclaredFields(); for (Field like : likefields) { like.setAccessible(true); if(tempChange.length()>0){ if(like.get(temp)!=null){ tempChange+="\n\t and "+like.getName()+" like '%"+like.get(temp)+"%'"; } }else { if(like.get(temp)!=null){ tempChange+="\n\t "+like.getName()+" like '%"+like.get(temp)+"%'"; } } } }if (baseCondition.getGroup_by()!=null) { if(tempChange.length()>0){ tempChange+="\n\t"+" "+"group by "+baseCondition.getGroup_by(); }else { tempChange+="\n\t"+baseCondition.getGroup_by(); } }if(baseCondition.getPage()!=null&&baseCondition.getPage().getBegin()!=null&&baseCondition.getPage().getEnd()!=null){ tempChange+="\n\tlimit ("+baseCondition.getPage().getBegin()+","+baseCondition.getPage().getEnd()+")"; } return tempChange; } private String getTempChange(Field[] fields,T pojo,JoinChoice join) throws Exception{ String tempsql = ""; for(int i=0;i<fields.length;i++){ fields[i].setAccessible(true); if(fields[i].get(pojo)!=null){ tempsql+=" "+fields[i].getName()+"="+"'"+fields[i].get(pojo)+"' "+join; } } tempsql=tempsql.substring(0,tempsql.length()-join.toString().length()); return tempsql; } }
package cn.com.commons.sql.file; import java.io.BufferedInputStream; import org.apache.log4j.Logger; /** * @author Administrator Feng * 2015-10-20 * 读取sql文件信息类 */ public class SQLFile { public static String getSQL(String sqlPath) { //log4j日志管理 Logger logger = Logger.getLogger(SQLFile.class); //创建流 BufferedInputStream inputStream = null ; //定义读取大小 byte[] size = new byte[1024]; int read =0; //sql StringBuffer sql = null ; try { sqlPath="sql-info/"+sqlPath; inputStream = new BufferedInputStream(SQLFile.class.getClassLoader().getResourceAsStream(sqlPath)); while ((read=inputStream.read(size))!=-1) { sql= new StringBuffer(new String(size, 0, read)); } //关闭流 inputStream.close(); logger.info(sql.toString()); //返回 return sql.toString(); } catch (Exception e) { logger.info(e.getMessage()); return null; } } }
猜你喜欢
请下载代码后再发表评论