日期:2014-05-17 浏览次数:20827 次
package cn.dao.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.engine.TypedValue;
public class Criterion implements org.hibernate.criterion.Criterion {
/**
*
*/
private static final long serialVersionUID = 1L;
public static enum CriterionType {
EQUAL, LIKE, COMPARE, NOT_LIKE
}
public static enum CompareType {
GT, GTE, LT, LTE, EQ, NE
}
private CriterionType criterionType;
private String tableName;
private String field;
private Object value;
// 将Criteria转换为SQL条件语句
public static String convertToSql(List<Criterion> criteria) {
String criteriaString = "";
StringBuilder sb = new StringBuilder();
for (Criterion criterion : criteria) {
String prefix = criterion.getFieldPrefix();
switch (criterion.getCriterionType()) {
case EQUAL:
sb.append(prefix + criterion.getField() + "=? and ");
break;
case LIKE:
sb.append(prefix + criterion.getField() + " like ? and ");
break;
case NOT_LIKE:
sb.append(prefix + criterion.getField() + " not like ? and ");
break;
case COMPARE:
CompareType compareType = ((CompareCriterion) criterion)
.getCompareType();
switch (compareType) {
case EQ:
sb.append(prefix + criterion.getField() + "=? and ");
break;
case NE:
sb.append(prefix + criterion.getField() + "<>? and ");
break;
case GT:
sb.append(prefix + criterion.getField() + ">? and ");
break;
case GTE:
sb.append(prefix + criterion.getField() + ">=? and ");
break;
case LT:
sb.append(prefix + criterion.getField() + "<? and ");
break;
case LTE:
sb.append(prefix + criterion.getField() + "<=? and ");
break;
}
break;
}
}
int i = -1;
if ((i = sb.lastIndexOf(" and ")) != -1) {
criteriaString = sb.substring(0, i);
}
return criteriaString;
}
// 将Criteria各条件的值转换为List<Object>
public static List<Object> getCriteriaValues(List<Criterion> criteria) {
List<Object> criteriaValues&n