hibernate工具类

jopen 12年前

GeneralDao.java

 import java.io.Serializable;  import java.lang.reflect.Field;  import java.lang.reflect.ParameterizedType;  import java.lang.reflect.Type;  import java.sql.ResultSet;  import java.sql.SQLException;  import java.sql.Statement;  import java.util.List;    import org.apache.commons.logging.Log;  import org.apache.commons.logging.LogFactory;  import org.hibernate.Criteria;  import org.hibernate.criterion.DetachedCriteria;  import org.hibernate.criterion.Projections;  import org.springframework.orm.hibernate3.support.HibernateDaoSupport;    public class GeneralDao<T extends Domain> extends HibernateDaoSupport implements    Serializable {     private static final long serialVersionUID = 3986291569067541566L;   private static final Log log = LogFactory.getLog(GeneralDao.class);     private Class<T> claz;   private List<Field> tableFields;     @SuppressWarnings("unchecked")   public GeneralDao() {    super();    Type type = this.getClass().getGenericSuperclass();    Type[] params = ((ParameterizedType) type).getActualTypeArguments();    claz = (Class<T>) params[0];    tableFields = HQLUtils.getTableFields(claz);   }     /**    * obj 增加    *     * @param obj    * @return    */   public Long save(T obj) {    return Long.valueOf(getHibernateTemplate().save(obj).toString());   }     /**    * obj 更新    *     * @param obj    */   public void update(T obj) {    getHibernateTemplate().update(obj);   }     /**    * 更新obj不为null的属性(根据ID更新)    *     * @param obj    */   public void updateNotNullField(T obj) {      if (obj != null && obj.getId() != null && obj.getId() > 0) {     T dbObj = get(obj.getId());     for (Field field : tableFields) {      try {       Object fieldValue = field.get(obj);       if (fieldValue != null) {        field.set(dbObj, fieldValue);       }      } catch (Exception e) {       log.error(         claz.getName() + "." + field.getName() + "属性取值错误",         e);      }     }     getHibernateTemplate().update(dbObj);    }     }     /**    * 根据ID查询obj    *     * @param id    * @return    */   public T get(Long id) {    return getHibernateTemplate().get(claz, id);   }     /**    * 根据ID删除    *     * @param id    */   public void deleteById(Long id) {    T obj = get(id);    getHibernateTemplate().delete(obj);   }     /**    * 删除对象    *     * @param obj    */   public void delete(T obj) {    getHibernateTemplate().delete(obj);   }     /**    * 查询所有记录    *     * @return    */   @SuppressWarnings("unchecked")   public List<T> getAll() {    return getHibernateTemplate().findByCriteria(getDetachedCriteria());   }     /**    * 查询记录总数    *     * @return    */   public Long getCount() {    return getCount(getDetachedCriteria());   }     /**    * 查询与obj中非空项相等的记录条数    *     * @param obj    * @return    */   public Long getCountEqNotNullField(T obj) {    return getCount(getDetachedCriteriaEqNotNullField(obj));   }     /**    * 查询与obj中非空项相等的记录    *     * @param obj    * @param begin    * @param count    * @param order    * @return    */   public List<T> getListEqNotNullField(T obj, Integer begin, Integer count,     OrderEnum order) {    return getList(getDetachedCriteriaEqNotNullField(obj), begin, count,      order);   }     /**    * 使用Statement.execute执行SQL    *     * @param sql    * @return    * @throws SQLException    */   protected Boolean runSQL(String sql) throws SQLException {    Statement st = super.getSession().connection().createStatement();    return st.execute(sql);   }     /**    * 使用Statement.executeQuery执行SQL    *     * @param sql    * @return    * @throws SQLException    */   protected ResultSet runQuerySQL(String sql) throws SQLException {    Statement st = super.getSession().connection().createStatement();    return st.executeQuery(sql);   }     /**    * 使用Statement.executeUpdate执行SQL    *     * @param sql    * @return    * @throws SQLException    */   protected Integer runUpdateSQL(String sql) throws SQLException {    Statement st = super.getSession().connection().createStatement();    return st.executeUpdate(sql);   }     /**    * 获得空查询条件对象    *     * @return    */   protected DetachedCriteria getDetachedCriteria() {    return getDetachedCriteriaEqNotNullField(null);   }     /**    * 获得查询条件对象,并对其填充obj的非null项等值查询条件    *     * @param obj    * @return    */   protected DetachedCriteria getDetachedCriteriaEqNotNullField(T obj) {      DetachedCriteria dc = DetachedCriteria.forClass(claz);      if (obj != null) {     for (Field field : tableFields) {      try {       Object fieldValue = field.get(obj);       if (fieldValue != null) {        HQLUtils.addEq(dc, field.getName(), fieldValue);       }      } catch (Exception e) {       log.error(         claz.getName() + "." + field.getName() + "属性取值错误",         e);      }     }    }      return dc;   }     /**    * 根据条件获得集合    *     * @param dc    * @param begin    * @param count    * @param order    * @return    */   @SuppressWarnings("unchecked")   protected List<T> getList(DetachedCriteria dc, Integer begin,     Integer count, OrderEnum order) {      dc = (dc == null ? getDetachedCriteria() : dc);      if (order != null) {     dc.addOrder(order.getValue());    }      if (begin != null && count != null) {     return getHibernateTemplate().findByCriteria(dc, begin, count);    }      return getHibernateTemplate().findByCriteria(dc);     }     /**    * 根据条件获得记录总数    *     * @param dc    * @return    */   protected Long getCount(DetachedCriteria dc) {    Criteria criteria = dc.getExecutableCriteria(this.getSession());    criteria.setProjection(Projections.rowCount());    Object results = criteria.uniqueResult();    return Long.valueOf(results.toString());   }    }

HQLUtils.java

 import java.lang.reflect.Field;  import java.util.ArrayList;  import java.util.Collection;  import java.util.List;    import javax.persistence.Column;    import org.apache.commons.lang.StringUtils;  import org.hibernate.criterion.DetachedCriteria;  import org.hibernate.criterion.MatchMode;  import org.hibernate.criterion.Restrictions;    public class HQLUtils {     /** > 操作 */   public final static String HQL_SIGN_GT = ">";   /** < 操作 */   public final static String HQL_SIGN_LT = "<";   /** = 操作 */   public final static String HQL_SIGN_EQ = "=";   /** >= 操作 */   public final static String HQL_SIGN_GE = ">=";   /** <= 操作 */   public final static String HQL_SIGN_LE = "<=";   /** != 操作 */   public final static String HQL_SIGN_NE = "!=";   /** between 操作 */   public final static String HQL_SIGN_BETWEEN = "between";   /** 为 null 操作 */   public final static String HQL_SIGN_NULL = "null";   /** 不为 null 操作 */   public final static String HQL_SIGN_NO_NULL = "notNull";   /** in 操作 */   public final static String HQL_SIGN_IN = "in";   /** like全匹配, 如%val% */   public final static String HQL_LIKE_ANYWHERE = "%val%";   /** like右匹配, 如val% */   public final static String HQL_LIKE_RIGHT = "val%";   /** like左匹配, 如%val */   public final static String HQL_LIKE_LEFT = "%val";   /** 拼接 纯SQL语句 操作 */   public final static String HQL_ADD_SQL = "sql";     /**    * 大于号拼接;key>value    *     * @param dc    * @param key    * @param value    */   public static void addGt(DetachedCriteria dc, String key, Object value) {    addSign(dc, HQL_SIGN_GT, key, value);   }     /**    * 小于号拼接;key<value    *     * @param dc    * @param key    * @param value    */   public static void addLt(DetachedCriteria dc, String key, Object value) {    addSign(dc, HQL_SIGN_LT, key, value);   }     /**    * 等于号拼接;key=value    *     * @param dc    * @param key    * @param value    */   public static void addEq(DetachedCriteria dc, String key, Object value) {    addSign(dc, HQL_SIGN_EQ, key, value);   }     /**    * 大于等于号拼接;key>=value    *     * @param dc    * @param key    * @param value    */   public static void addGe(DetachedCriteria dc, String key, Object value) {    addSign(dc, HQL_SIGN_GE, key, value);   }     /**    * 小于等于号拼接;key<=value    *     * @param dc    * @param key    * @param value    */   public static void addLe(DetachedCriteria dc, String key, Object value) {    addSign(dc, HQL_SIGN_LE, key, value);   }     /**    * 全like拼接; key like %value%    *     * @param dc    * @param key    * @param value    */   public static void addAnywhere(DetachedCriteria dc, String key, Object value) {    addSign(dc, HQL_LIKE_ANYWHERE, key, value);   }     /**    * 右like拼接; key like value%    *     * @param dc    * @param key    * @param value    */   public static void addRight(DetachedCriteria dc, String key, Object value) {    addSign(dc, HQL_LIKE_RIGHT, key, value);   }     /**    * 左like拼接; key like %value    *     * @param dc    * @param key    * @param value    */   public static void addLeft(DetachedCriteria dc, String key, Object value) {    addSign(dc, HQL_LIKE_LEFT, key, value);   }     /**    * 不等于号拼接; key != value    *     * @param dc    * @param key    * @param value    */   public static void addNe(DetachedCriteria dc, String key, Object value) {    addSign(dc, HQL_SIGN_NE, key, value);   }     /**    * 区间拼接; key between value1 and value2    *     * @param dc    * @param key    * @param value    */   public static void addBetween(DetachedCriteria dc, String key,     Object value1, Object value2) {    addSign(dc, HQL_SIGN_BETWEEN, key, value1, value2);   }     /**    * null值拼接;key is null    *     * @param dc    * @param key    */   public static void addNull(DetachedCriteria dc, String key) {    addSign(dc, HQL_SIGN_NULL, key);   }     /**    * null值拼接;key is not null    *     * @param dc    * @param key    */   public static void addNotNull(DetachedCriteria dc, String key) {    addSign(dc, HQL_SIGN_NO_NULL, key);   }     /**    * in 拼接;key in value1    *     * @param dc    * @param key    */   public static void addIn(DetachedCriteria dc, String key, Object value) {    addSign(dc, HQL_SIGN_IN, key, value);   }     /**    * sql 拼接;原dc的语句后接上key    *     * @param dc    * @param key    */   public static void addSQL(DetachedCriteria dc, String key) {    addSign(dc, HQL_ADD_SQL, key);   }     /**    * 根据符号拼接条件    *     * @param dc    * @param sign    *            符号    * @param key    * @param value    */   @SuppressWarnings("rawtypes")   public static void addSign(DetachedCriteria dc, String sign, String key,     Object... value) {      if (dc == null || StringUtils.isBlank(sign) || StringUtils.isBlank(key)) {     return;    }      if (HQL_SIGN_EQ.equals(sign)) {     dc.add(Restrictions.eq(key, value[0]));      } else if (HQL_SIGN_GT.equals(sign)) {     dc.add(Restrictions.gt(key, value[0]));      } else if (HQL_SIGN_LT.equals(sign)) {     dc.add(Restrictions.lt(key, value[0]));      } else if (HQL_SIGN_GE.equals(sign)) {     dc.add(Restrictions.ge(key, value[0]));      } else if (HQL_SIGN_LE.equals(sign)) {     dc.add(Restrictions.le(key, value[0]));      } else if (HQL_LIKE_ANYWHERE.equals(sign)) {     dc.add(Restrictions.like(key, String.valueOf(value[0]),       MatchMode.ANYWHERE));      } else if (HQL_LIKE_RIGHT.equals(sign)) {     dc.add(Restrictions.like(key, String.valueOf(value[0]),       MatchMode.START));      } else if (HQL_LIKE_LEFT.equals(sign)) {     dc.add(Restrictions.like(key, String.valueOf(value[0]),       MatchMode.END));      } else if (HQL_SIGN_NE.equals(sign)) {     dc.add(Restrictions.ne(key, value[0]));      } else if (HQL_SIGN_BETWEEN.equals(sign)) {     dc.add(Restrictions.between(key, value[0], value[1]));      } else if (HQL_SIGN_NULL.equals(sign)) {     dc.add(Restrictions.isNull(key));      } else if (HQL_SIGN_NO_NULL.equals(sign)) {     dc.add(Restrictions.isNotNull(key));      } else if (HQL_SIGN_IN.equals(sign)) {       if (value[0] instanceof Collection) {      dc.add(Restrictions.in(key, (Collection) value[0]));     } else {      dc.add(Restrictions.in(key, value));     }      } else if (HQL_ADD_SQL.equals(sign)) {     dc.add(Restrictions.sqlRestriction(key));    }     }     /**    * 获得与表有对应关系的类属性集合    *     * @param <T>    * @param claz    * @return    */   public static <T> List<Field> getTableFields(Class<T> claz) {    List<Field> list = new ArrayList<Field>();    Field[] fields = claz.getDeclaredFields();    for (Field field : fields) {     Column c = field.getAnnotation(Column.class);     if (c != null && StringUtils.isNotBlank(c.name())) {      list.add(field);     }    }    return list;   }    }

OrderEnum.java

 import org.hibernate.criterion.Order;    public enum OrderEnum {   /**    * ID倒序    */   IdDesc(Order.desc("id")),   /**    * ID正序    */   IdAsc(Order.asc("id"));     private Order value;     private OrderEnum(Order value) {    this.value = value;   }     public Order getValue() {    return value;   }    }

Domain.java

 import java.io.Serializable;    public interface Domain extends Serializable {     Long getId();     void setId(Long id);    }


好吧,上面的这4个文件放项目里呢,但怎么用呢?看下面:  OrderDetailDao.java文件:    public class OrderDetailDao extends GeneralDao<OrderDetail> {   private static final long serialVersionUID = -5007246085129055012L;  }    OrderDetail.java文件:    import javax.persistence.Column;  import javax.persistence.Entity;  import javax.persistence.GeneratedValue;  import javax.persistence.Id;  import javax.persistence.Table;  import javax.persistence.Transient;    import org.hibernate.annotations.GenericGenerator;    /**   * 订单明细   */  @Entity  @Table(name = "T_BIZ_ORDER_DETAIL")  @org.hibernate.annotations.Entity(mutable = true, dynamicInsert = true, dynamicUpdate = true)  @org.hibernate.annotations.Proxy(lazy = true)  @org.hibernate.annotations.Table(appliesTo = "T_BIZ_ORDER_DETAIL")  public class OrderDetail implements Domain {   private static final long serialVersionUID = -7113529240537274966L;     @Id   @GeneratedValue(generator = "identity")   @GenericGenerator(name = "identity", strategy = "identity")   @Column(name = "id", nullable = false, length = 19)   Long id; // 主键ID     @Column(name = "status", length = 50)   String status; // 1待审核,2审核通过,3审核失败     @Column(name = "exportStatus", length = 50)   String exportStatus;     @Column(name = "orderType", length = 50)   String orderType;     @Transient   String statusTxt;     public Long getId() {    return id;   }     public void setId(Long id) {    this.id = id;   }     public String getStatus() {    return status;   }     public void setStatus(String status) {    this.status = status;   }     public String getExportStatus() {    return exportStatus;   }     public void setExportStatus(String exportStatus) {    this.exportStatus = exportStatus;   }     public String getOrderType() {    return orderType;   }     public void setOrderType(String orderType) {    this.orderType = orderType;   }     public String getStatusTxt() {    return statusTxt;   }     public void setStatusTxt(String statusTxt) {    this.statusTxt = statusTxt;   }    }