论坛首页 入门技术论坛

spring集成的Hibernate一窥

浏览 5029 次
该帖已经被评为新手帖
作者 正文
   发表时间:2007-10-10  

在本篇中我大量引用的源代码,所以篇幅似乎有些冗长,为了阅读方便,已经明确标出和本文要讨论内容相近的部分,如果读者没有耐心,大可挑黑体部分浏览。

有一普通的DAO类如下:

public class BooksMapDao extends HibernateDaoSupport implements BooksDao {

    public BooksMapDao(){}

    public void addBook(Books book) {
        this.getHibernateTemplate().save(book);
    }


    public void deleteBook(Books book) {
        this.getHibernateTemplate().delete(book);
    }


    public List getAll() {
        String sql="FROM Books ORDER BY bookName";
        return this.getHibernateTemplate().find(sql);
    }

    public int getRows() {
        String sql="FROM Books ORDER BY bookName";
        List list=this.getHibernateTemplate().find(sql);
        return list.size();
    }
    

    public List getBooks(int pageSize, int startRow) throws HibernateException {
        final int pageSize1=pageSize;
        final int startRow1=startRow;
        return this.getHibernateTemplate().executeFind(new HibernateCallback(){

               public List doInHibernate(Session session) throws HibernateException, SQLException {
                // TODO 自动生成方法存根
                Query query=session.createQuery("FROM Books ORDER BY bookName");
                query.setFirstResult(startRow1);
                query.setMaxResults(pageSize1);
                return query.list();
            }
        });
    }


    public Books getBook(String bookId) {
        return (Books)this.getHibernateTemplate().get(Books.class,bookId);
    }


    public String getMaxID() {
        String date=PublicUtil.getStrNowDate();
        String sql="SELECT MAX(bookId)+1 FROM Books  ";
        String noStr = null;
        List ll = (List) this.getHibernateTemplate().find(sql);
        Iterator itr = ll.iterator();
        if (itr.hasNext()) {
            Object noint = itr.next();
            if(noint == null){
                noStr = "1";               
            }else{
                noStr = noint.toString();
            }
        }
       
        if(noStr.length()==1){
            noStr="000"+noStr;
        }else if(noStr.length()==2){
            noStr="00"+noStr;
        }else if(noStr.length()==3){
            noStr="0"+noStr;
        }else{
            noStr=noStr;
        }
        return noStr;
    }


    public void updateBook(Books pd) {
        this.getHibernateTemplate().update(pd);
    }

 
    public List queryBooks(String fieldname,String value) {
        System.out.println("value: "+value);
        String sql="FROM Books where "+fieldname+" like '%"+value+"%'"+"ORDER BY bookName";
        return this.getHibernateTemplate().find(sql);
    }
    
 
    public int getRows(String fieldname,String value) {
        String sql="";
        if(fieldname==null||fieldname.equals("")||fieldname==null||fieldname.equals(""))
            sql="FROM Books ORDER BY bookName";
        else   
            sql="FROM Books where "+fieldname+" like '%"+value+"%'"+"ORDER BY bookName";
        List list=this.getHibernateTemplate().find(sql);
        return list.size();
    }
    
    public List getBooks(String fieldname,String value,int pageSize, int startRow) {
        final int pageSize1=pageSize;
        final int startRow1=startRow;
        final String queryName=fieldname;
        final String queryValue=value;
        String sql="";
       
        if(queryName==null||queryName.equals("")||queryValue==null||queryValue.equals(""))
            sql="FROM Books ORDER BY bookName";
        else   
            sql="FROM Books where "+fieldname+" like '%"+value+"%'"+"ORDER BY bookName";
       
        final String sql1=sql;
        return this.getHibernateTemplate().executeFind(new HibernateCallback(){

            public List doInHibernate(Session session) throws HibernateException, SQLException {
                // TODO 自动生成方法存根
                Query query=session.createQuery(sql1);
                query.setFirstResult(startRow1);
                query.setMaxResults(pageSize1);
                return query.list();
            }
        });

    }

}

我们将重点看一下黑体字部分的实现来看看spring中的hibernate;

这个类继承自HibernateDaoSupport ,我们首先看一下spirng中HibernateDaoSupport 是如何实现的:;

public abstract class HibernateDaoSupport extends DaoSupport {

 private HibernateTemplate hibernateTemplate;


 public final void setSessionFactory(SessionFactory sessionFactory) {
   this.hibernateTemplate = createHibernateTemplate(sessionFactory);
 }

  protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) {
  return new HibernateTemplate(sessionFactory);
 }

 public final SessionFactory getSessionFactory() {
  return (this.hibernateTemplate != null ? this.hibernateTemplate.getSessionFactory() : null);
 }

 public final void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
  this.hibernateTemplate = hibernateTemplate;
 }

 public final HibernateTemplate getHibernateTemplate() {
   return this.hibernateTemplate;
 }

 protected final void checkDaoConfig() {
  if (this.hibernateTemplate == null) {
   throw new IllegalArgumentException("'sessionFactory' or 'hibernateTemplate' is required");
  }
 }


  protected final Session getSession()
   throws DataAccessResourceFailureException, IllegalStateException {

  return getSession(this.hibernateTemplate.isAllowCreate());
 }

  protected final Session getSession(boolean allowCreate)
     throws DataAccessResourceFailureException, IllegalStateException {

  return (!allowCreate ?
      SessionFactoryUtils.getSession(getSessionFactory(), false) :
    SessionFactoryUtils.getSession(
      getSessionFactory(),
      this.hibernateTemplate.getEntityInterceptor(),
      this.hibernateTemplate.getJdbcExceptionTranslator()));
 }

  protected final DataAccessException convertHibernateAccessException(HibernateException ex) {
  return this.hibernateTemplate.convertHibernateAccessException(ex);
 }

 protected final void releaseSession(Session session) {
  SessionFactoryUtils.releaseSession(session, getSessionFactory());
 }

}

这里可以看出,这个类中实现关于session和sessionfactory相关的一些功能模块,都很简单。其中有一个方法getHibernateTemplate()下面我们看一下spring是如何实现HibernateTemplate类的:

public class HibernateTemplate extends HibernateAccessor implements HibernateOperations {

 private boolean allowCreate = true;

 private boolean alwaysUseNewSession = false;

 private boolean exposeNativeSession = false;

 private boolean checkWriteOperations = true;

 private boolean cacheQueries = false;

 private String queryCacheRegion;

 private int fetchSize = 0;

 private int maxResults = 0;

 public HibernateTemplate() {
 }
 public HibernateTemplate(SessionFactory sessionFactory) {
  setSessionFactory(sessionFactory);
  afterPropertiesSet();
 }

 public HibernateTemplate(SessionFactory sessionFactory, boolean allowCreate) {
  setSessionFactory(sessionFactory);
  setAllowCreate(allowCreate);
  afterPropertiesSet();
 }
 public void setAllowCreate(boolean allowCreate) {
  this.allowCreate = allowCreate;
 }
 public boolean isAllowCreate() {
  return this.allowCreate;
 }

 public void setAlwaysUseNewSession(boolean alwaysUseNewSession) {
  this.alwaysUseNewSession = alwaysUseNewSession;
 }

 public boolean isAlwaysUseNewSession() {
  return this.alwaysUseNewSession;
 }

 public void setExposeNativeSession(boolean exposeNativeSession) {
  this.exposeNativeSession = exposeNativeSession;
 }
 public boolean isExposeNativeSession() {
  return this.exposeNativeSession;
 }

 public void setCheckWriteOperations(boolean checkWriteOperations) {
  this.checkWriteOperations = checkWriteOperations;
 }

 public boolean isCheckWriteOperations() {
  return this.checkWriteOperations;
 }

 public void setCacheQueries(boolean cacheQueries) {
  this.cacheQueries = cacheQueries;
 }
 public boolean isCacheQueries() {
  return this.cacheQueries;
 }
 public void setQueryCacheRegion(String queryCacheRegion) {
  this.queryCacheRegion = queryCacheRegion;
 }

 public String getQueryCacheRegion() {
  return this.queryCacheRegion;
 }

 public void setFetchSize(int fetchSize) {
  this.fetchSize = fetchSize;
 }
 public int getFetchSize() {
  return this.fetchSize;
 }

 public void setMaxResults(int maxResults) {
  this.maxResults = maxResults;
 }

 public int getMaxResults() {
  return this.maxResults;
 }


 public Object execute(HibernateCallback action) throws DataAccessException {
  return execute(action, isExposeNativeSession());
 }

 public List executeFind(HibernateCallback action) throws DataAccessException {
  Object result = execute(action, isExposeNativeSession());
  if (result != null && !(result instanceof List)) {
   throw new InvalidDataAccessApiUsageException(
     "Result object returned from HibernateCallback isn't a List: [" + result + "]");
  }
  return (List) result;
 }

 public Object execute(HibernateCallback action, boolean exposeNativeSession) throws DataAccessException {
  Assert.notNull(action, "Callback object must not be null");

  Session session = getSession();
  boolean existingTransaction = SessionFactoryUtils.isSessionTransactional(session, getSessionFactory());
  if (existingTransaction) {
   logger.debug("Found thread-bound Session for HibernateTemplate");
  }

  FlushMode previousFlushMode = null;
  try {
   previousFlushMode = applyFlushMode(session, existingTransaction);
   Session sessionToExpose = (exposeNativeSession ? session : createSessionProxy(session));
   Object result = action.doInHibernate(sessionToExpose);
   flushIfNecessary(session, existingTransaction);
   return result;
  }
  catch (HibernateException ex) {
   throw convertHibernateAccessException(ex);
  }
  catch (SQLException ex) {
   throw convertJdbcAccessException(ex);
  }
  catch (RuntimeException ex) {
   // Callback code threw application exception...
   throw ex;
  }
  finally {
   if (existingTransaction) {
    logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
    if (previousFlushMode != null) {
     session.setFlushMode(previousFlushMode);
    }
   }
   else {
    // Never use deferred close for an explicitly new Session.
    if (isAlwaysUseNewSession()) {
     SessionFactoryUtils.closeSession(session);
    }
    else {
     SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
    }
   }
  }
 }

 protected Session getSession() {
  if (isAlwaysUseNewSession()) {
   return SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor());
  }
  else if (!isAllowCreate()) {
   return SessionFactoryUtils.getSession(getSessionFactory(), false);
  }
  else {
   return SessionFactoryUtils.getSession(
     getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
  }
 }
 protected Session createSessionProxy(Session session) {
  return (Session) Proxy.newProxyInstance(
    getClass().getClassLoader(),
    new Class[] {Session.class},
    new CloseSuppressingInvocationHandler(session));
 }

 public Object get(Class entityClass, Serializable id) throws DataAccessException {
  return get(entityClass, id, null);
 }

 public Object get(final Class entityClass, final Serializable id, final LockMode lockMode)
   throws DataAccessException {

  return execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    if (lockMode != null) {
     return session.get(entityClass, id, lockMode);
    }
    else {
     return session.get(entityClass, id);
    }
   }
  }, true);
 }

 public Object load(Class entityClass, Serializable id) throws DataAccessException {
  return load(entityClass, id, null);
 }

 public Object load(final Class entityClass, final Serializable id, final LockMode lockMode)
   throws DataAccessException {

  return execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    if (lockMode != null) {
     return session.load(entityClass, id, lockMode);
    }
    else {
     return session.load(entityClass, id);
    }
   }
  }, true);
 }

 public List loadAll(final Class entityClass) throws DataAccessException {
  return (List) execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    Criteria criteria = session.createCriteria(entityClass);
    prepareCriteria(criteria);
    return criteria.list();
   }
  }, true);
 }

 public void load(final Object entity, final Serializable id) throws DataAccessException {
  execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    session.load(entity, id);
    return null;
   }
  }, true);
 }

 public void refresh(final Object entity) throws DataAccessException {
  refresh(entity, null);
 }

 public void refresh(final Object entity, final LockMode lockMode) throws DataAccessException {
  execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    if (lockMode != null) {
     session.refresh(entity, lockMode);
    }
    else {
     session.refresh(entity);
    }
    return null;
   }
  }, true);
 }

 public boolean contains(final Object entity) throws DataAccessException {
  Boolean result = (Boolean) execute(new HibernateCallback() {
   public Object doInHibernate(Session session) {
    return (session.contains(entity) ? Boolean.TRUE : Boolean.FALSE);
   }
  }, true);
  return result.booleanValue();
 }

 public void evict(final Object entity) throws DataAccessException {
  execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    session.evict(entity);
    return null;
   }
  }, true);
 }

 public void initialize(Object proxy) throws DataAccessException {
  try {
   Hibernate.initialize(proxy);
  }
  catch (HibernateException ex) {
   throw SessionFactoryUtils.convertHibernateAccessException(ex);
  }
 }

 public void lock(final Object entity, final LockMode lockMode) throws DataAccessException {
  execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    session.lock(entity, lockMode);
    return null;
   }
  }, true);
 }

 public Serializable save(final Object entity) throws DataAccessException {
  return (Serializable) execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    checkWriteOperationAllowed(session);
    return session.save(entity);
   }
  }, true);
 }

 public void save(final Object entity, final Serializable id) throws DataAccessException {
  execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    checkWriteOperationAllowed(session);
    session.save(entity, id);
    return null;
   }
  }, true);
 }

 public void update(Object entity) throws DataAccessException {
  update(entity, null);
 }

 public void update(final Object entity, final LockMode lockMode) throws DataAccessException {
  execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    checkWriteOperationAllowed(session);
    session.update(entity);
    if (lockMode != null) {
     session.lock(entity, lockMode);
    }
    return null;
   }
  }, true);
 }

 public void saveOrUpdate(final Object entity) throws DataAccessException {
  execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    checkWriteOperationAllowed(session);
    session.saveOrUpdate(entity);
    return null;
   }
  }, true);
 }

 public void saveOrUpdateAll(final Collection entities) throws DataAccessException {
  execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    checkWriteOperationAllowed(session);
    for (Iterator it = entities.iterator(); it.hasNext();) {
     session.saveOrUpdate(it.next());
    }
    return null;
   }
  }, true);
 }

 public Object saveOrUpdateCopy(final Object entity) throws DataAccessException {
  return execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    checkWriteOperationAllowed(session);
    return session.saveOrUpdateCopy(entity);
   }
  }, true);
 }

 public void replicate(final Object entity, final ReplicationMode replicationMode)
   throws DataAccessException {

  execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    checkWriteOperationAllowed(session);
    session.replicate(entity, replicationMode);
    return null;
   }
  }, true);
 }

 public void delete(Object entity) throws DataAccessException {
  delete(entity, null);
 }

 public void delete(final Object entity, final LockMode lockMode) throws DataAccessException {
  execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    checkWriteOperationAllowed(session);
    if (lockMode != null) {
     session.lock(entity, lockMode);
    }
    session.delete(entity);
    return null;
   }
  }, true);
 }

 public void deleteAll(final Collection entities) throws DataAccessException {
  execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    checkWriteOperationAllowed(session);
    for (Iterator it = entities.iterator(); it.hasNext();) {
     session.delete(it.next());
    }
    return null;
   }
  }, true);
 }

 public void flush() throws DataAccessException {
  execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    session.flush();
    return null;
   }
  }, true);
 }

 public void clear() throws DataAccessException {
  execute(new HibernateCallback() {
   public Object doInHibernate(Session session) {
    session.clear();
    return null;
   }
  }, true);
 }


 public List find(String queryString) throws DataAccessException {
  return find(queryString, (Object[]) null, (Type[]) null);
 }

 public List find(String queryString, Object value) throws DataAccessException {
  return find(queryString, new Object[] {value}, (Type[]) null);
 }

 public List find(String queryString, Object value, Type type) throws DataAccessException {
  return find(queryString, new Object[] {value}, new Type[] {type});
 }

 public List find(String queryString, Object[] values) throws DataAccessException {
  return find(queryString, values, (Type[]) null);
 }

 public List find(final String queryString, final Object[] values, final Type[] types)
   throws DataAccessException {

  if (values != null && types != null && values.length != types.length) {
   throw new IllegalArgumentException("Length of values array must match length of types array");
  }
  return (List) execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    Query queryObject = session.createQuery(queryString);
    prepareQuery(queryObject);
    if (values != null) {
     for (int i = 0; i < values.length; i++) {
      if (types != null && types[i] != null) {
       queryObject.setParameter(i, values[i], types[i]);
      }
      else {
       queryObject.setParameter(i, values[i]);
      }
     }
    }
    return queryObject.list();
   }
  }, true);
 }

 public List findByNamedParam(String queryString, String paramName, Object value)
   throws DataAccessException {

  return findByNamedParam(queryString, paramName, value, null);
 }

 public List findByNamedParam(String queryString, String paramName, Object value, Type type)
   throws DataAccessException {

  return findByNamedParam(queryString, new String[] {paramName}, new Object[] {value}, new Type[] {type});
 }

 public List findByNamedParam(String queryString, String[] paramNames, Object[] values)
   throws DataAccessException {

  return findByNamedParam(queryString, paramNames, values, null);
 }

 public List findByNamedParam(
     final String queryString, final String[] paramNames, final Object[] values, final Type[] types)
     throws DataAccessException {

  if (paramNames.length != values.length) {
   throw new IllegalArgumentException("Length of paramNames array must match length of values array");
  }
  if (types != null && paramNames.length != types.length) {
   throw new IllegalArgumentException("Length of paramNames array must match length of types array");
  }
  return (List) execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    Query queryObject = session.createQuery(queryString);
    prepareQuery(queryObject);
    if (values != null) {
     for (int i = 0; i < values.length; i++) {
      applyNamedParameterToQuery(queryObject, paramNames[i], values[i], (types != null ? types[i] : null));
     }
    }
    return queryObject.list();
   }
  }, true);
 }

 public List findByValueBean(final String queryString, final Object valueBean)
   throws DataAccessException {

  return (List) execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    Query queryObject = session.createQuery(queryString);
    prepareQuery(queryObject);
    queryObject.setProperties(valueBean);
    return queryObject.list();
   }
  }, true);
 }

 public List findByNamedQuery(String queryName) throws DataAccessException {
  return findByNamedQuery(queryName, (Object[]) null, (Type[]) null);
 }

 public List findByNamedQuery(String queryName, Object value) throws DataAccessException {
  return findByNamedQuery(queryName, new Object[] {value}, (Type[]) null);
 }

 public List findByNamedQuery(String queryName, Object value, Type type) throws DataAccessException {
  return findByNamedQuery(queryName, new Object[] {value}, new Type[] {type});
 }

 public List findByNamedQuery(String queryName, Object[] values) throws DataAccessException {
  return findByNamedQuery(queryName, values, (Type[]) null);
 }

 public List findByNamedQuery(final String queryName, final Object[] values, final Type[] types)
   throws DataAccessException {

  if (values != null && types != null && values.length != types.length) {
   throw new IllegalArgumentException("Length of values array must match length of types array");
  }
  return (List) execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    Query queryObject = session.getNamedQuery(queryName);
    prepareQuery(queryObject);
    if (values != null) {
     for (int i = 0; i < values.length; i++) {
      if (types != null && types[i] != null) {
       queryObject.setParameter(i, values[i], types[i]);
      }
      else {
       queryObject.setParameter(i, values[i]);
      }
     }
    }
    return queryObject.list();
   }
  }, true);
 }

 public List findByNamedQueryAndNamedParam(String queryName, String paramName, Object value)
   throws DataAccessException {

  return findByNamedQueryAndNamedParam(queryName, paramName, value, null);
 }

 public List findByNamedQueryAndNamedParam(String queryName, String paramName, Object value, Type type)
   throws DataAccessException {

  return findByNamedQueryAndNamedParam(
    queryName, new String[] {paramName}, new Object[] {value}, new Type[] {type});
 }

 public List findByNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values)
   throws DataAccessException {

  return findByNamedQueryAndNamedParam(queryName, paramNames, values, null);
 }

 public List findByNamedQueryAndNamedParam(
     final String queryName, final String[] paramNames, final Object[] values, final Type[] types)
     throws DataAccessException {

  if (paramNames != null && values != null && paramNames.length != values.length) {
   throw new IllegalArgumentException("Length of paramNames array must match length of values array");
  }
  if (values != null && types != null && paramNames.length != types.length) {
   throw new IllegalArgumentException("Length of paramNames array must match length of types array");
  }
  return (List) execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    Query queryObject = session.getNamedQuery(queryName);
    prepareQuery(queryObject);
    if (values != null) {
     for (int i = 0; i < values.length; i++) {
      applyNamedParameterToQuery(queryObject, paramNames[i], values[i], (types != null ? types[i] : null));
     }
    }
    return queryObject.list();
   }
  }, true);
 }

 public List findByNamedQueryAndValueBean(final String queryName, final Object valueBean)
   throws DataAccessException {

  return (List) execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    Query queryObject = session.getNamedQuery(queryName);
    prepareQuery(queryObject);
    queryObject.setProperties(valueBean);
    return queryObject.list();
   }
  }, true);
 }

 public Iterator iterate(String queryString) throws DataAccessException {
  return iterate(queryString, (Object[]) null, (Type[]) null);
 }

 public Iterator iterate(String queryString, Object value) throws DataAccessException {
  return iterate(queryString, new Object[] {value}, (Type[]) null);
 }

 public Iterator iterate(String queryString, Object value, Type type)
   throws DataAccessException {

  return iterate(queryString, new Object[] {value}, new Type[] {type});
 }

 public Iterator iterate(String queryString, Object[] values) throws DataAccessException {
  return iterate(queryString, values, (Type[]) null);
 }

 public Iterator iterate(final String queryString, final Object[] values, final Type[] types)
   throws DataAccessException {

  if (values != null && types != null && values.length != types.length) {
   throw new IllegalArgumentException("Length of values array must match length of types array");
  }
  return (Iterator) execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    Query queryObject = session.createQuery(queryString);
    prepareQuery(queryObject);
    if (values != null) {
     for (int i = 0; i < values.length; i++) {
      if (types != null && types[i] != null) {
       queryObject.setParameter(i, values[i], types[i]);
      }
      else {
       queryObject.setParameter(i, values[i]);
      }
     }
    }
    return queryObject.iterate();
   }
  }, true);
 }

 public void closeIterator(Iterator it) throws DataAccessException {
  try {
   Hibernate.close(it);
  }
  catch (HibernateException ex) {
   throw SessionFactoryUtils.convertHibernateAccessException(ex);
  }
 }

 public int delete(String queryString) throws DataAccessException {
  return delete(queryString, (Object[]) null, (Type[]) null);
 }

 public int delete(String queryString, Object value, Type type)
   throws DataAccessException {

  return delete(queryString, new Object[] {value}, new Type[] {type});
 }

 public int delete(final String queryString, final Object[] values, final Type[] types)
   throws DataAccessException {

  if (values != null && types != null && values.length != types.length) {
   throw new IllegalArgumentException("Length of values array must match length of types array");
  }
  Integer deleteCount = (Integer) execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    checkWriteOperationAllowed(session);
    if (values != null) {
     return new Integer(session.delete(queryString, values, types));
    }
    else {
     return new Integer(session.delete(queryString));
    }
   }
  }, true);
  return deleteCount.intValue();
 }


 protected void checkWriteOperationAllowed(Session session) throws InvalidDataAccessApiUsageException {
  if (isCheckWriteOperations() && getFlushMode() != FLUSH_EAGER &&
    FlushMode.NEVER.equals(session.getFlushMode())) {
   throw new InvalidDataAccessApiUsageException(
     "Write operations are not allowed in read-only mode (FlushMode.NEVER): "+
     "Turn your Session into FlushMode.AUTO or remove 'readOnly' marker from transaction definition.");
  }
 }

 protected void prepareQuery(Query queryObject) {
  if (isCacheQueries()) {
   queryObject.setCacheable(true);
   if (getQueryCacheRegion() != null) {
    queryObject.setCacheRegion(getQueryCacheRegion());
   }
  }
  if (getFetchSize() > 0) {
   queryObject.setFetchSize(getFetchSize());
  }
  if (getMaxResults() > 0) {
   queryObject.setMaxResults(getMaxResults());
  }
  SessionFactoryUtils.applyTransactionTimeout(queryObject, getSessionFactory());
 }

 protected void prepareCriteria(Criteria criteria) {
  if (isCacheQueries()) {
   criteria.setCacheable(true);
   if (getQueryCacheRegion() != null) {
    criteria.setCacheRegion(getQueryCacheRegion());
   }
  }
  if (getFetchSize() > 0) {
   criteria.setFetchSize(getFetchSize());
  }
  if (getMaxResults() > 0) {
   criteria.setMaxResults(getMaxResults());
  }
  SessionFactoryUtils.applyTransactionTimeout(criteria, getSessionFactory());
 }
 protected void applyNamedParameterToQuery(Query queryObject, String paramName, Object value, Type type)
   throws HibernateException {

  if (value instanceof Collection) {
   if (type != null) {
    queryObject.setParameterList(paramName, (Collection) value, type);
   }
   else {
    queryObject.setParameterList(paramName, (Collection) value);
   }
  }
  else if (value instanceof Object[]) {
   if (type != null) {
    queryObject.setParameterList(paramName, (Object[]) value, type);
   }
   else {
    queryObject.setParameterList(paramName, (Object[]) value);
   }
  }
  else {
   if (type != null) {
    queryObject.setParameter(paramName, value, type);
   }
   else {
    queryObject.setParameter(paramName, value);
   }
  }
 }

 private class CloseSuppressingInvocationHandler implements InvocationHandler {

  private final Session target;

  public CloseSuppressingInvocationHandler(Session target) {
   this.target = target;
  }

  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   // Invocation on Session interface coming in...

   if (method.getName().equals("equals")) {
    // Only consider equal when proxies are identical.
    return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE);
   }
   else if (method.getName().equals("hashCode")) {
    // Use hashCode of Session proxy.
    return new Integer(hashCode());
   }
   else if (method.getName().equals("close")) {
    // Handle close method: suppress, not valid.
    return null;
   }

   // Invoke method on target Session.
   try {
    Object retVal = method.invoke(this.target, args);

    // If return value is a Query or Criteria, apply transaction timeout.
    // Applies to createQuery, getNamedQuery, createCriteria.
    if (retVal instanceof Query) {
     prepareQuery(((Query) retVal));
    }
    if (retVal instanceof Criteria) {
     prepareCriteria(((Criteria) retVal));
    }

    return retVal;
   }
   catch (InvocationTargetException ex) {
    throw ex.getTargetException();
   }
  }
 }

}

这个类提供了非常丰富的方法,以方便开发人员使用。我们重点看一下黑体字标出的三个方法,特别是红体字标出的方法。

public Object execute(HibernateCallback action) throws DataAccessException;

public Object execute(HibernateCallback action, boolean exposeNativeSession) throws DataAccessException;

public List executeFind(HibernateCallback action) throws DataAccessException;

前两个方法实现了重载,我们从源代码可以看到,其实真正实现功能的方法是上面列出的第二个方法。我们可以注意到它们的方法有一个共同的HibernateCallback 参数,我们看一下HibernateCallback 的声明:

public interface HibernateCallback {
 Object doInHibernate(Session session) throws HibernateException, SQLException;

}

我们可以看到这个接口只是定义了一个方法doInHibernate,传入参数Session ,返回类型Object。我们知道java类都直接或间接继承自Object类,这样的话就等于给了我们就可以非常灵活的返回我们所需要的任何类型。传入参数是Session,这样我们就可以客户化的实现自己所需要的功能。这样既对spring中的HibernateTemplate 进行了扩展,有同时可以满足客户化的需要。

 

看完所有这些代码我们再来看我们最开始那部分代码就非常的明了了。

作者通过调用spring的executeFind方法,传入了一个实现了doInHibernate方法的匿名类。匿名类的好处这里就不再说了。
 

   发表时间:2007-10-10  
把代码放到code里面会好看很多
0 请登录后投票
   发表时间:2007-10-10  
没看懂想表达什么,画几个类图不是关系更清晰吗?
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics