使用注解和spring的JdbcTemplate进行封装实现类似Hibernate的功能
工具类DBUtils:
/** 2014-05修改 增加对查询语句的缓存 增加对jdbcTemplt查询出的Map转换成Bean的方法 */ private static Logger log = Logger.getLogger(SQLUtils.class); private static Map cacheMap = new HashMap(); private static Map insertSqlCache = new HashMap(); private static Map updateSqlCache = new HashMap(); private static Map deleteSqlCache = new HashMap(); private static Map selectSqlCache = new HashMap(); /** * 根据pojo类的class来构建select * from 的SQL语句 * @param pojoClass * @return */ public static String buildSelectSql(Class pojoClass){ List<FieldInfo> fieldInfoList = loadPojoSqlInfo(pojoClass); String sql = buildSelectSql(pojoClass, fieldInfoList); if(log.isDebugEnabled()){ log.debug("select sql is:"+sql); } return sql; } /** * 根据pojo类的class来构建insert的SQL语句 * @param pojoClass * @return */ public static String buildInsertSql(Class pojoClass){ List<FieldInfo> fieldInfoList = loadPojoSqlInfo(pojoClass); String sql = buildInsertSql(pojoClass, fieldInfoList); if(log.isDebugEnabled()){ log.debug("insert sql is:"+sql); } return sql; } /** * 根据pojo类的class构建根据pk来update的SQL语句 * @param pojoObject * @return */ public static String buildUpdateSql(Class pojoClass){ List<FieldInfo> fieldInfoList = loadPojoSqlInfo(pojoClass); String sql = buildUpdateSqlByPK(pojoClass, fieldInfoList); if(log.isDebugEnabled()){ log.debug("update sql is:"+sql); } return sql; } /** * 根据pojo类的Class和更新的条件字段来生成upate的SQL语句 * @param pojoClass * @param columns * @return * @throws Exception */ public static String buildUpdateSqlByColumns(Class pojoClass,String[] columns) throws Exception{ if(null!=columns && columns.length>0){ List<FieldInfo> fieldInfoList = loadPojoSqlInfo(pojoClass); String sql = buildUpdateSqlByColumns(pojoClass, fieldInfoList, columns); if(log.isDebugEnabled()){ log.debug("update sql is:"+sql); } return sql; }else{ if(log.isDebugEnabled()){ log.debug("生成update sql error! 参数columns必须有值" ); } throw new Exception("参数columns必须有值!"); } } /** * 根据pojo类的Class生成根据pk来delete的SQL语句 * @param pojoClass * @return */ public static String buildDeleteSql(Class pojoClass){ List<FieldInfo> fieldInfoList = loadPojoSqlInfo(pojoClass); String sql = buildDeleteSqlByPK(pojoClass,fieldInfoList); if(log.isDebugEnabled()){ log.debug("delete sql is:"+sql); } return sql; } /** * 根据pojo类的Class和更新的条件字段来生成delete的SQL语句 * @param pojoClass * @param columns * @return * @throws Exception */ public static String buildDeleteSqlByColumns(Class pojoClass,String[] columns) throws Exception{ if(null!=columns && columns.length>0){ List<FieldInfo> fieldInfoList = loadPojoSqlInfo(pojoClass); String sql = buildDeleteSqlByColumns(pojoClass, fieldInfoList, columns); if(log.isDebugEnabled()){ log.debug("delete sql is:"+sql); } return sql; }else{ if(log.isDebugEnabled()){ log.debug("生成delete sql error! 参数columns必须有值" ); } throw new Exception("参数columns必须有值!"); } } /** * 将SQL查询出来的map对象转成实体对象 * @param map * @param pojoClass * @return * @throws Exception */ public static Object coverMapToBean(Map map,Class pojoClass) throws Exception{ Object result = pojoClass.newInstance(); List<FieldInfo> list = loadPojoSqlInfo(pojoClass); for(FieldInfo fieldInfo : list){ String dbName = fieldInfo.getDbFieldName().toUpperCase(); String fieldName = fieldInfo.getPojoFieldName(); String setMethoName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); if(map.get(dbName)!=null){ Method m = pojoClass.getMethod(setMethoName, fieldInfo.getType()); m.invoke(result, map.get(dbName)); } } return result; } /** * 加载读取pojo的注解信息 * @param pojoClass * @return */ @SuppressWarnings("unchecked") private static List<FieldInfo> loadPojoSqlInfo(Class pojoClass){ List<FieldInfo> resultList = null; if(null == cacheMap.get(pojoClass.getName())){ resultList = new ArrayList<FieldInfo>(); Field[] fields = pojoClass.getDeclaredFields(); for(Field field : fields){ FieldInfo fieldInfo = new FieldInfo(); fieldInfo.setPojoFieldName(field.getName()); if(field.isAnnotationPresent(com.test.anno.Field.class)){ String value = ((com.test.anno.Field)field.getAnnotation(com.test.anno.Field.class)).value();//得到配置的数据库字段名 if(StringUtils.isEmpty(value)){//没有设置数据库的字段名,则取pojo的字段名 fieldInfo.setDbFieldName(lowerStrToUnderline(field.getName())); }else{ fieldInfo.setDbFieldName(value); } }else{ fieldInfo.setDbFieldName(lowerStrToUnderline(field.getName())); } if(field.isAnnotationPresent(com.test.anno.PK.class)){ fieldInfo.setIsPk(true); } if(field.isAnnotationPresent(com.test.anno.NoInsert.class)){ fieldInfo.setIsInsert(false); } if(field.isAnnotationPresent(com.test.anno.NoUpdate.class)){ fieldInfo.setIsUpdate(false); } fieldInfo.setType(field.getType()); resultList.add(fieldInfo); } cacheMap.put(pojoClass.getName(), resultList); }else{ resultList = (List<FieldInfo>)cacheMap.get(pojoClass.getName()); } return resultList; } /** * 评价select语句 * @param pojoClass * @param fieldInfoList * @return */ private static String buildSelectSql(Class pojoClass,List<FieldInfo> fieldInfoList){ if(selectSqlCache.get(pojoClass.getName()) != null){ return (String)selectSqlCache.get(pojoClass.getName()); } return "select * from " + loadTableName(pojoClass); } /** * 拼接insert的SQL * @param pojoClass * @param fieldInfoList * @return */ @SuppressWarnings("unchecked") private static String buildInsertSql(Class pojoClass,List<FieldInfo> fieldInfoList){ String result = null; if(insertSqlCache.get(pojoClass.getName()) != null){ result = (String)insertSqlCache.get(pojoClass.getName()); return result; } String tableName = loadTableName(pojoClass); StringBuffer temp1 = new StringBuffer(); StringBuffer temp2 = new StringBuffer(); for(FieldInfo fieldInfo : fieldInfoList){ if(fieldInfo.getIsInsert()){ temp1.append(fieldInfo.getDbFieldName()).append(","); temp2.append(":").append(fieldInfo.getPojoFieldName()).append(","); } } temp1.deleteCharAt(temp1.length()-1); temp2.deleteCharAt(temp2.length()-1); StringBuffer resultSql = new StringBuffer(); resultSql.append("insert into "); resultSql.append(tableName); resultSql.append("("); resultSql.append(temp1); resultSql.append(") values ("); resultSql.append(temp2); resultSql.append(")"); result = resultSql.toString(); insertSqlCache.put(pojoClass.getName(), result); return result; } /** * 生成根据主键生成删除的SQL * @param pojoClass * @param fieldInfoList * @return */ @SuppressWarnings("unchecked") private static String buildDeleteSqlByPK(Class pojoClass,List<FieldInfo> fieldInfoList){ String result = null; if(deleteSqlCache.get(pojoClass.getName()+"_pk") != null){ result = (String)deleteSqlCache.get(pojoClass.getName()); return result; } StringBuffer resultSql = new StringBuffer(); resultSql.append(appendBaseDeleteSQL(pojoClass)); for(FieldInfo fieldInfo : fieldInfoList){ if(fieldInfo.getIsPk()){ resultSql.append(fieldInfo.getDbFieldName()); resultSql.append("=:").append(fieldInfo.getPojoFieldName()).append(" and "); } } resultSql.delete(resultSql.length()-4, resultSql.length()); result = resultSql.toString(); deleteSqlCache.put(pojoClass.getName()+"_pk", result); return result; } /** * 拼接根据主键来update的SQL * @param pojoClass * @param fieldInfoList * @return */ @SuppressWarnings("unchecked") private static String buildUpdateSqlByPK(Class pojoClass, List<FieldInfo> fieldInfoList){ String result = null; if(updateSqlCache.get(pojoClass.getName()+"_pk") != null){ result = (String)updateSqlCache.get(pojoClass.getName()+"_pk"); return result; } StringBuffer resultSql = new StringBuffer(); resultSql.append(appendBaseUpdateSQL(pojoClass, fieldInfoList)); for(FieldInfo fieldInfo : fieldInfoList){ if(fieldInfo.getIsPk()){ resultSql.append(fieldInfo.getDbFieldName()); resultSql.append("=:").append(fieldInfo.getPojoFieldName()).append(" and "); } } resultSql.delete(resultSql.length()-4, resultSql.length()); result = resultSql.toString(); updateSqlCache.put(pojoClass.getName()+"_pk", result); return result; } /** * 根据用户指定的更新条件(字段)来生成update的SQL * @param pojoClass * @param fieldInfoList * @param columns * @return */ private static String buildUpdateSqlByColumns(Class pojoClass, List<FieldInfo> fieldInfoList,String[] columns){ StringBuffer resultSql = new StringBuffer(); if(updateSqlCache.get(pojoClass.getName()+"_columns") != null){ resultSql.append((String)updateSqlCache.get(pojoClass.getName()+"_columns")); }else{ resultSql.append(appendBaseUpdateSQL(pojoClass, fieldInfoList)); } for(String column : columns){ for(FieldInfo fieldInfo : fieldInfoList){ if(column.equals(fieldInfo.getPojoFieldName())){ resultSql.append(fieldInfo.getDbFieldName()); resultSql.append("=:").append(column).append(" and "); break; } } } resultSql.delete(resultSql.length()-4, resultSql.length()); return resultSql.toString(); } /** * 拼接update语句的where之前的sql * @param pojoClass * @param fieldInfoList * @param resultSql */ @SuppressWarnings("unchecked") private static String appendBaseUpdateSQL(Class pojoClass, List<FieldInfo> fieldInfoList){ String result = null; if(updateSqlCache.get(pojoClass.getName()+"_columns") != null){ result = (String)updateSqlCache.get(pojoClass.getName()+"_columns"); }else{ StringBuffer resultSql = new StringBuffer(); String tableName = loadTableName(pojoClass); resultSql.append("update ").append(tableName).append(" set "); for(FieldInfo fieldInfo : fieldInfoList){ if(fieldInfo.getIsUpdate() && !fieldInfo.getIsPk()){ resultSql.append(fieldInfo.getDbFieldName()); resultSql.append("=:").append(fieldInfo.getPojoFieldName()).append(","); } } resultSql.deleteCharAt(resultSql.length()-1); resultSql.append(" where "); result = resultSql.toString(); updateSqlCache.put(pojoClass.getName()+"_columns", result); } return result; } /** * 根据用户指定的更新条件(字段)来生成delete的SQL * @param pojoClass * @param fieldInfoList * @param columns * @return */ private static String buildDeleteSqlByColumns(Class pojoClass, List<FieldInfo> fieldInfoList,String[] columns){ StringBuffer resultSql = new StringBuffer(); if(deleteSqlCache.get(pojoClass.getName()+"_columns") != null){ resultSql.append((String)deleteSqlCache.get(pojoClass.getName()+"_columns")); }else{ resultSql.append(appendBaseUpdateSQL(pojoClass, fieldInfoList)); } for(String column : columns){ for(FieldInfo fieldInfo : fieldInfoList){ if(column.equals(fieldInfo.getPojoFieldName())){ resultSql.append(fieldInfo.getDbFieldName()); resultSql.append("=:").append(column).append(" and "); break; } } } resultSql.delete(resultSql.length()-4, resultSql.length()); return resultSql.toString(); } /** * 拼接delete语句的where之前的sql * @param pojoClass * @param fieldInfoList * @param resultSql */ @SuppressWarnings("unchecked") private static String appendBaseDeleteSQL(Class pojoClass){ if(deleteSqlCache.get(pojoClass.getName()+"_columns") != null){ return (String)deleteSqlCache.get(pojoClass.getName()+"_columns"); }else{ String result = "delete from " + loadTableName(pojoClass) + " where "; deleteSqlCache.put(pojoClass.getName()+"_columns", result); return result; } } /** * 通过类获取表名 * @param pojoClass * @return */ @SuppressWarnings("unchecked") private static String loadTableName(Class pojoClass){ if(pojoClass.isAnnotationPresent(Table.class)){ Table table = (Table)pojoClass.getAnnotation(Table.class); return table.value(); }else{ return lowerStrToUnderline(pojoClass.getSimpleName()); } } /** * 将大写字母转换成下划线加小写字母 * 例:userName--> user_name * @param str * @return */ private static String lowerStrToUnderline(String str) { if(StringUtils.isEmpty(str)){ return ""; } StringBuilder sb = new StringBuilder(str); char c; int count = 0; for (int i = 0; i < str.length(); i++) { c = str.charAt(i); if (c >= 'A' && c <= 'Z') { sb.replace(i+count, i+count+1, (c+"").toLowerCase()); sb.insert(i+count, "_"); count++; } } return sb.toString(); }
注解类:
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Field { //数据库字段名 public String value() default ""; }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface NoInsert { }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface NoUpdate { }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface PK { }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Table { public String value(); }
用来保存pojo类的字段信息的类:
public class FieldInfo { //java字段名 private String pojoFieldName; //数据库字段名 private String dbFieldName; //是否是主键 private boolean isPk = false; //update时是否需要更新 private boolean isUpdate = true; //insert时是否需要插入 private boolean isInsert = true; public boolean isPk() { return isPk; } public void setIsPk(boolean isPk) { this.isPk = isPk; } public boolean isUpdate() { return isUpdate; } public void setIsUpdate(boolean isUpdate) { this.isUpdate = isUpdate; } public String getPojoFieldName() { return pojoFieldName; } public void setPojoFieldName(String pojoFieldName) { this.pojoFieldName = pojoFieldName; } public String getDbFieldName() { return dbFieldName; } public void setDbFieldName(String dbFieldName) { this.dbFieldName = dbFieldName; } public boolean isInsert() { return isInsert; } public void setIsInsert(boolean isInsert) { this.isInsert = isInsert; } }
pojo类:
@Table("t_log") public class WorkLog { //id @PK @Field("id") private String logId ; //日志日期 @NoUpdate private Date logDate; //log_date //所属项目 private String projectId; //工作类型 private String jobTypeId; //日志内容 private String content; //工作时长 private double workTime; //填写时间 private Timestamp fillTime; //日志填写人 @NoUpdate private String employeeId; //状态 @NoUpdate private String archivingState; //.....get set method }
分装一个基础的操作的BaseDao类(这里只封装了几个常用的CRUD操作,具体运用可以再增加):
@Resource private JdbcTemplate jdbcTemplate; @Resource private NamedParameterJdbcTemplate namedParameterJdbcTemplate; /** * 保存新增的实体对象 * @param bean * @return */ public boolean baseSave(Object bean){ String sql = SQLUtils.buildInsertSql(bean.getClass()); SqlParameterSource sps = new BeanPropertySqlParameterSource(bean); return this.namedParameterJdbcTemplate.update(sql, sps)>0? true:false; } /** * 根据主键保存修改的实体对象 * @param bean * @return */ public boolean baseSaveUpdate(Object bean){ String sql = SQLUtils.buildUpdateSql(bean.getClass()); SqlParameterSource sps = new BeanPropertySqlParameterSource(bean); return this.namedParameterJdbcTemplate.update(sql, sps)>0? true:false; } /** * 根据bean的部分字段的条件来更新bean的信息 * @param bean * @param fileds * @return * @throws Exception */ public boolean baseSaveUpdateWithColumn(Object bean,String[] fileds) throws Exception{ String sql = SQLUtils.buildUpdateSqlByColumns(bean.getClass(), fileds); SqlParameterSource sps = new BeanPropertySqlParameterSource(bean); return this.namedParameterJdbcTemplate.update(sql, sps)>0? true:false; } /** * 根据bean的pk来删除bean * @param bean * @return */ public boolean baseDelete(Object bean){ String sql = SQLUtils.buildDeleteSql(bean.getClass()); SqlParameterSource sps = new BeanPropertySqlParameterSource(bean); return this.namedParameterJdbcTemplate.update(sql, sps)>0? true:false; } /** * 根据bean的部分字段的条件来删除bean * @param bean * @param fileds * @return * @throws Exception */ public boolean baseDeleteWithColumn(Object bean,String[] fileds) throws Exception{ String sql = SQLUtils.buildDeleteSqlByColumns(bean.getClass(), fileds); SqlParameterSource sps = new BeanPropertySqlParameterSource(bean); return this.namedParameterJdbcTemplate.update(sql, sps)>0? true:false; } /** * 自动分页/不分页查询返回list * @param cs * @param conditionDef * @param paramMap * @return */ public List baseQueryForList(Class cs, ConditionDef conditionDef, Map paramMap){ Condition condition=new Condition(conditionDef,paramMap); String sql = SQLUtils.buildSelectSql(cs) + condition.getConditionClauseWithWhere(); if(PagingUtils.isPagingSearchRequest(paramMap)) { return PagingUtils.pagingQuery(namedParameterJdbcTemplate, sql, paramMap); }else { return namedParameterJdbcTemplate.queryForList(sql, paramMap); } } /** * 查询满足条件的单条记录的实体对象,如果超过1条则抛出异常,没查询到则返回null * @param cs * @param conditionDef * @param paramMap * @return * @throws Exception */ public Object baseQueryForEntity(Class cs, ConditionDef conditionDef, Map paramMap) throws Exception{ Condition condition=new Condition(conditionDef,paramMap); String sql = SQLUtils.buildSelectSql(cs) + condition.getConditionClauseWithWhere(); List list = this.namedParameterJdbcTemplate.queryForList(sql, paramMap); if(null==list || list.size()==0 || list.size()>1){ return null; }else if(list.size()>1){ throw new Exception("query return record more then one!!"); }else{ Map map = (Map)list.get(0); return SQLUtils.coverMapToBean(map, cs); } } public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() { return namedParameterJdbcTemplate; }
对查询参数进行封装的类:
ConditionDef.java
public class ConditionDef { private Map<String, String> paraNameAndSubConditionClauseMap = new LinkedHashMap(); private Map<String, Class> paraNameAndClassTypeMap = new HashMap(); private Map<String, List<Character>> paraNameAndLikeMatchInfoMap = new HashMap(); public ConditionDef(Object[][] defineArr) { for (Object[] subDefine : defineArr) { Pattern pattern = Pattern.compile(":([\\w\\d_]+)"); String currDefClause = (String) subDefine[0]; int currDefClauseLen = currDefClause.length(); Matcher matcher = pattern.matcher(currDefClause); //System.out.println(currDefClause); Set varNameSet = new HashSet(); int varNameCount = 0; char clauseMode = Condition.STANDARD_MODE; String oneVarName = null; boolean isUsedSameMatchMode=true; List<Character> matchModeList=new ArrayList(); while (matcher.find()) { String varName = matcher.group(1); oneVarName = varName; int start = matcher.start(); int end = matcher.end(); char prefix = currDefClause.charAt(start - 1); char suffix = end >= currDefClauseLen ? ' ' : currDefClause.charAt(end); char subConditionMatchMode = Condition.STANDARD_MODE; if (prefix == '%' && suffix == '%') { clauseMode = subConditionMatchMode = Condition.GLOBAL_MATCH; matchModeList.add(clauseMode); } else if (prefix == '%') { clauseMode = subConditionMatchMode = Condition.PREFIX_MATCH; matchModeList.add(clauseMode); } else if (suffix == '%') { clauseMode = subConditionMatchMode = Condition.SUFFIX_MATCH; matchModeList.add(clauseMode); } varNameSet.add(varName); varNameCount++; if(varNameCount>1&&matchModeList.size()>=2) { int size=matchModeList.size(); if(!matchModeList.get(size-1).equals(matchModeList.get(size-2))) { isUsedSameMatchMode=false; } } } if (varNameSet.size() != 1) { throw new RuntimeException("One sub condition clause must only have one var name ! clause :" + currDefClause); } if (oneVarName == null) { throw new RuntimeException("Sub condition is not have any var name ! clause :" + currDefClause); } if (subDefine.length > 1) { paraNameAndClassTypeMap.put(oneVarName, (Class) subDefine[1]); //System.out.println("save var type : " + oneVarName + "," + ((Class) subDefine[1]).getSimpleName()); } if (clauseMode != Condition.STANDARD_MODE) { if (isUsedSameMatchMode&&varNameCount==matchModeList.size()) { paraNameAndLikeMatchInfoMap.put(oneVarName, matchModeList.subList(0,1)); } else { currDefClause=currDefClause.replaceAll("%:"+oneVarName+"%", ":"+oneVarName+"_globalMatch"); currDefClause=currDefClause.replaceAll("%:"+oneVarName, ":"+oneVarName+"_suffixMatch"); currDefClause=currDefClause.replaceAll(":"+oneVarName+"%", ":"+oneVarName+"_prefixMatch"); paraNameAndLikeMatchInfoMap.put(oneVarName, matchModeList); } currDefClause = currDefClause.replaceAll("'\\%", ""); currDefClause = currDefClause.replaceAll("\\%'", ""); currDefClause = currDefClause.replaceAll("\\%", ""); currDefClause = currDefClause.replaceAll("'", ""); //System.out.println("processed clause : " + currDefClause); } String tempClause=currDefClause.toUpperCase(); if(tempClause.indexOf("AND")!=-1||tempClause.indexOf("OR")!=-1) { currDefClause="("+currDefClause+")"; } paraNameAndSubConditionClauseMap.put(oneVarName, currDefClause); } } public String[] getConditionVarNames() { // TODO Auto-generated method stub return paraNameAndSubConditionClauseMap.keySet().toArray(new String[paraNameAndSubConditionClauseMap.keySet().size()]); } public String getSubConditionClause(String varName) { // TODO Auto-generated method stub return paraNameAndSubConditionClauseMap.get(varName); } public boolean isExistClassTypeInfo(String varName) { // TODO Auto-generated method stub return paraNameAndClassTypeMap.containsKey(varName); } public Class getClassTypeInfo(String varName) { // TODO Auto-generated method stub return paraNameAndClassTypeMap.get(varName); } public boolean isExistMatchModeInfo(String varName) { // TODO Auto-generated method stub return paraNameAndLikeMatchInfoMap.containsKey(varName); } public List<Character> getMatchModeInfo(String varName) { // TODO Auto-generated method stub return paraNameAndLikeMatchInfoMap.get(varName); } }
Condition.java
public class Condition { public static final String AND = " AND "; public static final String OR = " OR "; public static final char PREFIX_MATCH = 'P'; public static final char SUFFIX_MATCH = 'S'; public static final char GLOBAL_MATCH = 'G'; public static final char LIKE_MODE = 'L'; public static final char STANDARD_MODE = 0; List<Integer> varTypesList = new ArrayList(); private String conditionClauseStr = ""; private String relateOperate = AND; public Condition(ConditionDef def, Map valueMap) { this(def, valueMap, AND); } public Condition(ConditionDef def, Map valueMap, String relateOperate) { this.relateOperate = relateOperate; String[] varNameArr = def.getConditionVarNames(); List<String> usedSubConditionClauseList = new ArrayList(); for (String varName : varNameArr) { if (!StringUtils.isEmpty(valueMap.get(varName))) { usedSubConditionClauseList.add(def.getSubConditionClause(varName)); Object priValue = valueMap.get(varName); if (def.isExistClassTypeInfo(varName)) { Class targetClass = def.getClassTypeInfo(varName); Object newValue = null; if (targetClass == java.sql.Date.class) { newValue = java.sql.Date.valueOf((String)priValue); valueMap.put(varName, newValue); } else if (targetClass == java.sql.Timestamp.class) { newValue = java.sql.Timestamp.valueOf((String)priValue); valueMap.put(varName, newValue); } else if (targetClass == java.sql.Time.class) { newValue = java.sql.Time.valueOf((String)priValue); valueMap.put(varName, newValue); } else if (targetClass == java.util.List.class) { List valueList=new ArrayList(); if (priValue.getClass().isArray()){ String[] valueArr=(String[])priValue; for (String string : valueArr) { valueList.add(string); } }else{ valueList.add(priValue); } valueMap.put(varName, valueList); } } if (def.isExistMatchModeInfo(varName)) { List<Character> matchModeList = def.getMatchModeInfo(varName); if (matchModeList.size() == 1) { if (matchModeList.get(0) == Condition.GLOBAL_MATCH) { priValue = "%" + priValue + "%"; } else if (matchModeList.get(0) == Condition.PREFIX_MATCH) { priValue = priValue + "%"; } else if (matchModeList.get(0) == Condition.SUFFIX_MATCH) { priValue = "%" + priValue; } valueMap.put(varName , priValue); } else { for (char currMatchMode : matchModeList) { if (currMatchMode == Condition.GLOBAL_MATCH) { String newValue = "%" + priValue + "%"; valueMap.put(varName + "_globalMatch", newValue); } else if (currMatchMode == Condition.PREFIX_MATCH) { String newValue = priValue + "%"; valueMap.put(varName + "_prefixMatch", newValue); } else if (currMatchMode == Condition.SUFFIX_MATCH) { String newValue = "%" + priValue; valueMap.put(varName + "_suffixMatch", newValue); } } } } } } this.conditionClauseStr = StringUtils.join(usedSubConditionClauseList, relateOperate); } public String getConditionClause() { return this.conditionClauseStr; } public String getConditionClauseWithWhere() { return "".equals(conditionClauseStr)?"":" WHERE " + conditionClauseStr; } public String getConditionClauseWithStartRelateOperatorIfNeeded() { if(conditionClauseStr.trim().equals("")) { return ""; }else { return this.relateOperate + " " + conditionClauseStr; } } public String getConditionClauseWithRelateOperatorAtStart() { return this.relateOperate + " " + conditionClauseStr; } public Integer[] getConditionVarTypes() { return varTypesList.toArray(new Integer[]{}); } }
调用Dao:
public class TestDao extends BaseDao{ private ConditionDef conditionDef=new ConditionDef( new Object[][] { {"DEPTNO = :deptno"}, {"MGRNO = :mgrno"} } ); public List query(Map paramMap){ return this.baseQueryForList(Department.class, conditionDef, paramMap); } public void save(){ Department dep = new Department(); dep.setDeptno("S22"); dep.setDeptname("my depart"); dep.setMgrno("000060"); dep.setAdmrdept("E01"); dep.setLocation("haha"); this.baseSave(dep); } public void update() throws Exception{ Map paramMap = new HashMap(); paramMap.put("deptno", "S22"); Object o = this.baseQueryForEntity(Department.class, conditionDef, paramMap); Department dept = null; if(o!=null){ dept = (Department)o; dept.setLocation("update"); this.baseSaveUpdate(dept); } } public void delete(){ Department dept = new Department(); dept.setDeptno("S22"); this.baseDelete(dept); } }