文章目录

hibernate Synchronizer 是一款生成hibernate cfg、hbm、pojo、dao代码的工具。相比较其它的同类工具,hibernate Synchronizer生成的代码比较优秀,还有它的同步功能,可以为我们省去很多时间,但遗憾的时,他不支持Spring DAO的生成。

hibernate Synchronizer生成的DAO是自带session管理了,如果单纯的给其DAO加上HibernateDaoSupport就是导致混乱。而且发现其DAO是以单例方式存在的。

幸好hibernate Synchronizer 的生成代码方式是基于模版方式,这就给了很大的空间来编写自己的模版,来生成代码。

下面我就贴一个自己写的BaseRootDao,去掉了其自带的Session管理代码,修改了原来的方法,以基于HibernateDaoSupport。

 

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public abstract class BaseRootDAO extends HibernateDaoSupport {
 /*
 
Logger for this class
  */
 private static final Logger log = Logger.getLogger(BaseRootDAO.class);

 /*
 
Return the specific Object class that will be used for class-specific
  implementation of this DAO.
 

  @return the reference Class
 
/
 protected abstract Class getReferenceClass();

 /*
 
Used by the base DAO classes but here for your modification Get object
  matching the given key and return it.
 
/
 protected Object get(Class refClass, Serializable key) {
  log.debug("get " + refClass + " instance with id: " + key);
  try {
   // 使用getHibernateTemplate()去操作DB。
   return getHibernateTemplate().get(refClass, key);
  } catch (RuntimeException re) {
   log.error("get failed", re);
   throw re;
  }

 }

 /*
 
Used by the base DAO classes but here for your modification Load object
  matching the given key and return it.
 
/
 protected Object load(Class refClass, Serializable key) {
  log.debug("load " + refClass + " instance with id: " + key);
  try {
   // 使用getHibernateTemplate()去操作DB。
   return getHibernateTemplate().load(refClass, key);
  } catch (RuntimeException re) {
   log.error("load failed", re);
   throw re;
  }

 }

 /*
 
Return all objects related to the implementation of this DAO with no
  filter.
 
/
 public java.util.List findAll() {

  return findAll(getDefaultOrder());

 }

 /*
 
Return all objects related to the implementation of this DAO with no
  filter. Use the session given.
 

  @param s
 
            the Session
  */
 public java.util.List findAll(Order defaultOrder) {

  DetachedCriteria crit = DetachedCriteria.forClass(getReferenceClass());
  if (null != defaultOrder)
   crit.addOrder(defaultOrder);
  return getHibernateTemplate().findByCriteria(crit);

 }

 /*
 
@param crit
  @return
 
/
 public java.util.List findByDetachedCriteria(DetachedCriteria crit) {
  return getHibernateTemplate().findByCriteria(crit);
 }

 /*
 
Return all objects related to the implementation of this DAO with a
  filter. Use the session given.
 

  @param propName
 
            the name of the property to use for filtering
  @param filter
 
            the value of the filter
  */
 protected DetachedCriteria findFiltered(String propName, Object filter) {
  return findFiltered(propName, filter, getDefaultOrder());
 }

 /*
 
Return all objects related to the implementation of this DAO with a
  filter. Use the session given.
 

  @param s
 
            the Session
  @param propName
 
            the name of the property to use for filtering
  @param filter
 
            the value of the filter
  @param orderProperty
 
            the name of the property used for ordering
  */
 protected DetachedCriteria findFiltered(String propName, Object filter,
   Order order) {
  DetachedCriteria crit = DetachedCriteria.forClass(getReferenceClass());
  crit.add(Expression.eq(propName, filter));
  if (null != order)
   crit.addOrder(order);
  return crit;
 }

 protected Order getDefaultOrder() {
  return null;
 }

 /*
 
Used by the base DAO classes but here for your modification Persist the
  given transient instance, first assigning a generated identifier. (Or
 
using the current value of the identifier property if the assigned
  generator is used.)
 
/
 protected Serializable save(final Object obj) {
  return getHibernateTemplate().save(obj);
 }

 /*
 
Used by the base DAO classes but here for your modification Either save()
  or update() the given instance, depending upon the value of its
 
identifier property.
  */
 protected void saveOrUpdate(final Object obj) {
  getHibernateTemplate().saveOrUpdate(obj);

 }

 /*
 
Used by the base DAO classes but here for your modification Update the
  persistent state associated with the given identifier. An exception is
 
thrown if there is a persistent instance with the same identifier in the
  current session.
 

  @param obj
 
            a transient instance containing updated state
  */
 protected void update(final Object obj) {

  getHibernateTemplate().update(obj);

 }

 /*
 
Delete all objects returned by the query
  */
 protected int delete(final Collection query) {
  int size = query.size();
  getHibernateTemplate().deleteAll(query);
  return size;
 }

 /*
 
Used by the base DAO classes but here for your modification Remove a
  persistent instance from the datastore. The argument may be an instance
 
associated with the receiving Session or a transient instance with an
  identifier associated with exi
sting persistent state.
 
/
 protected void delete(final Object obj) {
  getHibernateTemplate().delete(obj);
 }

 /*
 
Used by the base DAO classes but here for your modification Re-read the
  state of the given instance from the underlying database. It is
 
inadvisable to use this to implement long-running sessions that span many
  business tasks. This method is, however, useful in certain special
 
circumstances.
  */
 protected void refresh(Object obj) {
  getHibernateTemplate().refresh(obj);

 }

 protected void throwException(Throwable t) {
  if (t instanceof HibernateException)
   throw (HibernateException) t;
  else if (t instanceof RuntimeException)
   throw (RuntimeException) t;
  else
   throw new HibernateException(t);
 }

 // 當遇到HibernateTemplate沒提供,非用session才行的時候,用這種方式寫成HibernateCallback。
 // 原則還是讓session交給Spring去管理。
 public java.util.List findBySQL(final String queryString,
   final String alias, final Class refClass) {
  log.debug("findBySQL queryString " + queryString);
  return (List) getHibernateTemplate().execute(new HibernateCallback() {
   public Object doInHibernate(Session session)
     throws HibernateException {
    SQLQuery sqlQ = session.createSQLQuery(queryString);
    if (alias == null) {
     sqlQ.addEntity(refClass == null ? getReferenceClass()
       : refClass);
    } else {
     sqlQ.addEntity(alias,
       refClass == null ? getReferenceClass() : refClass);
    }
    return sqlQ.list();
   }
  }, true);
 }

 

文章目录