工具类DBUtils:
/**2014-05修改
增加对查询语句的缓存
增加对jdbcTemplt查询出的Map转换成Bean的方法*/privatestaticLogger log = Logger.getLogger(SQLUtils.class);
privatestaticMap cacheMap =new HashMap();
privatestaticMap insertSqlCache =new HashMap();
privatestaticMap updateSqlCache =new HashMap();
privatestaticMap deleteSqlCache =new HashMap();
privatestaticMap selectSqlCache =new HashMap();
/** * 根据pojo类的class来构建select * from 的SQL语句
* @param pojoClass
* @return*/publicstatic String buildSelectSql(Class pojoClass){
List 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*/publicstatic String buildInsertSql(Class pojoClass){
List 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*/publicstatic String buildUpdateSql(Class pojoClass){
List 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
*/publicstaticString buildUpdateSqlByColumns(Class pojoClass,String[] columns)throws Exception{
if(null!=columns && columns.length>0){
List 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必须有值" );
}
thrownewException("参数columns必须有值!");
}
}
/** * 根据pojo类的Class生成根据pk来delete的SQL语句
* @param pojoClass
* @return*/publicstatic String buildDeleteSql(Class pojoClass){
List 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
*/publicstaticString buildDeleteSqlByColumns(Class pojoClass,String[] columns)throws Exception{
if(null!=columns && columns.length>0){
List 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必须有值" );
}
thrownewException("参数columns必须有值!");
}
}
/** * 将SQL查询出来的map对象转成实体对象
* @param map
* @param pojoClass
* @return * @throws Exception
*/publicstaticObject coverMapToBean(Map map,Class pojoClass)throws Exception{
Object result = pojoClass.newInstance();
List 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")
privatestaticList loadPojoSqlInfo(Class pojoClass){
List resultList =null;
if(null== cacheMap.get(pojoClass.getName())){
resultList =newArrayList();
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)cacheMap.get(pojoClass.getName());
}
return resultList;
}
/** * 评价select语句
* @param pojoClass
* @param fieldInfoList
* @return*/privatestaticString buildSelectSql(Class pojoClass,List 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")
privatestaticString buildInsertSql(Class pojoClass,List 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")
privatestaticString buildDeleteSqlByPK(Class pojoClass,List 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")
privatestaticString buildUpdateSqlByPK(Class pojoClass, List 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*/privatestaticString buildUpdateSqlByColumns(Class pojoClass, List 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")
privatestaticString appendBaseUpdateSQL(Class pojoClass, List 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*/privatestaticString buildDeleteSqlByColumns(Class pojoClass, List 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")
privatestatic 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")
privatestatic 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*/privatestatic String lowerStrToUnderline(String str) {
if(StringUtils.isEmpty(str)){
return"";
}
StringBuilder sb =new StringBuilder(str);
char c;
intcount = 0;
for(inti = 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 {
//数据库字段名publicString 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类的字段信息的类:
publicclass FieldInfo {
//java字段名private String pojoFieldName;
//数据库字段名private String dbFieldName;
//是否是主键privatebooleanisPk =false;
//update时是否需要更新privatebooleanisUpdate =true;
//insert时是否需要插入privatebooleanisInsert =true;
publicboolean isPk() {
return isPk;
}
publicvoidsetIsPk(boolean isPk) {
this.isPk = isPk;
}
publicboolean isUpdate() {
return isUpdate;
}
publicvoidsetIsUpdate(boolean isUpdate) {
this.isUpdate = isUpdate;
}
public String getPojoFieldName() {
return pojoFieldName;
}
publicvoid setPojoFieldName(String pojoFieldName) {
this.pojoFieldName = pojoFieldName;
}
public String getDbFieldName() {
return dbFieldName;
}
publicvoid setDbFieldName(String dbFieldName) {
this.dbFieldName = dbFieldName;
}
publicboolean isInsert() {
return isInsert;
}
publicvoidsetIsInsert(boolean isInsert) {
this.isInsert = isInsert;
}
}
pojo类:
@Table("t_log")publicclass WorkLog {
//id @PK
@Field("id")
private String logId ;
//日志日期 @NoUpdate
privateDate logDate;//log_date
//所属项目private String projectId;
//工作类型private String jobTypeId;
//日志内容private String content;
//工作时长privatedouble 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*/publicboolean baseSave(Object bean){
String sql = SQLUtils.buildInsertSql(bean.getClass());
SqlParameterSource sps =new BeanPropertySqlParameterSource(bean);
returnthis.namedParameterJdbcTemplate.update(sql, sps)>0?true:false;
}
/** * 根据主键保存修改的实体对象
* @param bean
* @return*/publicboolean baseSaveUpdate(Object bean){
String sql = SQLUtils.buildUpdateSql(bean.getClass());
SqlParameterSource sps =new BeanPropertySqlParameterSource(bean);
returnthis.namedParameterJdbcTemplate.update(sql, sps)>0?true:false;
}
/** * 根据bean的部分字段的条件来更新bean的信息
* @param bean
* @param fileds
* @return * @throws Exception
*/publicbooleanbaseSaveUpdateWithColumn(Object bean,String[] fileds)throws Exception{
String sql = SQLUtils.buildUpdateSqlByColumns(bean.getClass(), fileds);
SqlParameterSource sps =new BeanPropertySqlParameterSource(bean);
returnthis.namedParameterJdbcTemplate.update(sql, sps)>0?true:false;
}
/** * 根据bean的pk来删除bean
* @param bean
* @return*/publicboolean baseDelete(Object bean){
String sql = SQLUtils.buildDeleteSql(bean.getClass());
SqlParameterSource sps =new BeanPropertySqlParameterSource(bean);
returnthis.namedParameterJdbcTemplate.update(sql, sps)>0?true:false;
}
/** * 根据bean的部分字段的条件来删除bean
* @param bean
* @param fileds
* @return * @throws Exception
*/publicbooleanbaseDeleteWithColumn(Object bean,String[] fileds)throws Exception{
String sql = SQLUtils.buildDeleteSqlByColumns(bean.getClass(), fileds);
SqlParameterSource sps =new BeanPropertySqlParameterSource(bean);
returnthis.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
*/publicObject 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){
returnnull;
}elseif(list.size()>1){
thrownewException("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
publicclass ConditionDef {
privateMap paraNameAndSubConditionClauseMap =new LinkedHashMap();
privateMap paraNameAndClassTypeMap =new HashMap();
privateMap> paraNameAndLikeMatchInfoMap =new HashMap();
public ConditionDef(Object[][] defineArr) {
for (Object[] subDefine : defineArr) {
Pattern pattern = Pattern.compile(":([\\w\\d_]+)");
String currDefClause = (String) subDefine[0];
intcurrDefClauseLen = currDefClause.length();
Matcher matcher = pattern.matcher(currDefClause);
//System.out.println(currDefClause);Set varNameSet =new HashSet();
intvarNameCount = 0;
charclauseMode = Condition.STANDARD_MODE;
String oneVarName =null;
booleanisUsedSameMatchMode=true;
List matchModeList=new ArrayList();
while (matcher.find()) {
String varName = matcher.group(1);
oneVarName = varName;
intstart = matcher.start();
intend = matcher.end();
charprefix = currDefClause.charAt(start - 1);
charsuffix = end >= currDefClauseLen ? ' ' : currDefClause.charAt(end);
charsubConditionMatchMode = Condition.STANDARD_MODE;
if(prefix == '%' && suffix == '%') {
clauseMode = subConditionMatchMode = Condition.GLOBAL_MATCH;
matchModeList.add(clauseMode);
} elseif(prefix == '%') {
clauseMode = subConditionMatchMode = Condition.PREFIX_MATCH;
matchModeList.add(clauseMode);
} elseif(suffix == '%') {
clauseMode = subConditionMatchMode = Condition.SUFFIX_MATCH;
matchModeList.add(clauseMode);
}
varNameSet.add(varName);
varNameCount++;
if(varNameCount>1&&matchModeList.size()>=2) {
intsize=matchModeList.size();
if(!matchModeList.get(size-1).equals(matchModeList.get(size-2))) {
isUsedSameMatchMode=false;
}
}
}
if(varNameSet.size() != 1) {
thrownewRuntimeException("One sub condition clause must only have one var name ! clause :" + currDefClause);
}
if(oneVarName ==null) {
thrownewRuntimeException("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 stubreturnparaNameAndSubConditionClauseMap.keySet().toArray(new String[paraNameAndSubConditionClauseMap.keySet().size()]);
}
public String getSubConditionClause(String varName) {
// TODO Auto-generated method stubreturn paraNameAndSubConditionClauseMap.get(varName);
}
publicboolean isExistClassTypeInfo(String varName) {
// TODO Auto-generated method stubreturn paraNameAndClassTypeMap.containsKey(varName);
}
public Class getClassTypeInfo(String varName) {
// TODO Auto-generated method stubreturn paraNameAndClassTypeMap.get(varName);
}
publicboolean isExistMatchModeInfo(String varName) {
// TODO Auto-generated method stubreturn paraNameAndLikeMatchInfoMap.containsKey(varName);
}
publicList getMatchModeInfo(String varName) {
// TODO Auto-generated method stubreturn paraNameAndLikeMatchInfoMap.get(varName);
}
}
Condition.java
publicclass Condition {
publicstaticfinalString AND = " AND ";
publicstaticfinalString OR = " OR ";
publicstaticfinalcharPREFIX_MATCH = 'P';
publicstaticfinalcharSUFFIX_MATCH = 'S';
publicstaticfinalcharGLOBAL_MATCH = 'G';
publicstaticfinalcharLIKE_MODE = 'L';
publicstaticfinalcharSTANDARD_MODE = 0;
List varTypesList =new ArrayList();
privateString conditionClauseStr = "";
privateString 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 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);
} elseif(targetClass == java.sql.Timestamp.class) {
newValue = java.sql.Timestamp.valueOf((String)priValue);
valueMap.put(varName, newValue);
} elseif(targetClass == java.sql.Time.class) {
newValue = java.sql.Time.valueOf((String)priValue);
valueMap.put(varName, newValue);
} elseif(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 matchModeList = def.getMatchModeInfo(varName);
if(matchModeList.size() == 1) {
if(matchModeList.get(0) == Condition.GLOBAL_MATCH) {
priValue = "%" + priValue + "%";
} elseif(matchModeList.get(0) == Condition.PREFIX_MATCH) {
priValue = priValue + "%";
} elseif(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);
} elseif(currMatchMode == Condition.PREFIX_MATCH) {
String newValue = priValue + "%";
valueMap.put(varName + "_prefixMatch", newValue);
} elseif(currMatchMode == Condition.SUFFIX_MATCH) {
String newValue = "%" + priValue;
valueMap.put(varName + "_suffixMatch", newValue);
}
}
}
}
}
}
this.conditionClauseStr = StringUtils.join(usedSubConditionClauseList, relateOperate);
}
public String getConditionClause() {
returnthis.conditionClauseStr;
}
public String getConditionClauseWithWhere() {
return"".equals(conditionClauseStr)?"":" WHERE " + conditionClauseStr;
}
public String getConditionClauseWithStartRelateOperatorIfNeeded() {
if(conditionClauseStr.trim().equals("")) {
return"";
}else {
returnthis.relateOperate + " " + conditionClauseStr;
}
}
public String getConditionClauseWithRelateOperatorAtStart() {
returnthis.relateOperate + " " + conditionClauseStr;
}
public Integer[] getConditionVarTypes() {
returnvarTypesList.toArray(new Integer[]{});
}
}
调用Dao:
publicclassTestDaoextends BaseDao{
privateConditionDef conditionDef=new ConditionDef(
new Object[][] {
{"DEPTNO = :deptno"},
{"MGRNO = :mgrno"}
}
);
public List query(Map paramMap){
returnthis.baseQueryForList(Department.class, conditionDef, paramMap);
}
publicvoid save(){
Department dep =new Department();
dep.setDeptno("S22");
dep.setDeptname("my depart");
dep.setMgrno("000060");
dep.setAdmrdept("E01");
dep.setLocation("haha");
this.baseSave(dep);
}
publicvoidupdate()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);
}
}
publicvoid delete(){
Department dept =new Department();
dept.setDeptno("S22");
this.baseDelete(dept);
}
}
网友评论