`
giga_Zhang
  • 浏览: 155280 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

spring集成的Hibernate一窥

阅读更多

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

有一普通的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方法的匿名类。匿名类的好处这里就不再说了。
 

分享到:
评论
2 楼 wangzhongjie 2007-10-10  
没看懂想表达什么,画几个类图不是关系更清晰吗?
1 楼 laiseeme 2007-10-10  
把代码放到code里面会好看很多

相关推荐

    Spring与Hibernate集成

    **Spring与Hibernate集成详解** 在Java企业级应用开发中,Spring和Hibernate是两个非常重要的框架。Spring是一个全方位的轻量级应用框架,提供了强大的依赖注入、AOP(面向切面编程)以及各种服务管理功能。而...

    Spring集成Hibernate所需jar包

    在Java企业级开发中,Spring和Hibernate是两个非常重要的框架,Spring作为一个全面的轻量级容器,负责管理和协调应用组件,而Hibernate则是一个强大的对象关系映射(ORM)框架,处理数据库交互。将这两个框架集成...

    ssh集成jar包,支持spring集成Hibernate,spring集成struts2等

    在Java开发领域,SSH(Spring、Struts2、Hibernate)是一个经典的开源框架组合,用于构建高效、可维护的企业级Web应用程序。这些框架分别负责不同层面的任务:Spring作为基础架构框架,提供依赖注入和AOP(面向切面...

    Spring集成Hibernate myeclipse 下

    Spring是一个全面的Java企业级应用开发框架,提供了依赖注入、AOP(面向切面编程)、MVC(模型-视图-控制器)等特性,而Hibernate则是一个优秀的对象关系映射(ORM)工具,它简化了Java应用与数据库之间的交互。...

    Spring2 Hibernate3集成

    Spring与Hibernate的集成是现代Java企业级应用开发中非常常见的模式之一。通过对Spring提供的事务管理和DAO支持的充分利用,以及Hibernate提供的强大ORM能力,可以构建出高效且易于维护的应用程序。在实际开发过程中...

    spring集成hibernate所需jar包

    Spring作为一个全面的轻量级框架,提供了强大的依赖注入、AOP(面向切面编程)以及各种企业级服务,而Hibernate则是Java世界中流行的ORM解决方案,简化了数据库操作。将Spring与Hibernate集成,可以充分利用两者的...

    Spring之Spring2.5集成Hibernate3.6

    这篇博客“Spring之Spring2.5集成Hibernate3.6”主要探讨了如何将两个经典的开源框架——Spring 2.5和Hibernate 3.6进行整合,以实现数据持久化的高效管理。 Spring 2.5版本是Spring框架的一个重要里程碑,它引入了...

    struts2 spring hibernate集成

    集成Struts2、Spring和Hibernate时,需要注意配置文件的正确设置,包括Action配置、Spring Bean的定义、Hibernate的数据库连接和实体映射。同时,理解这三个框架的工作原理和相互作用,对于解决问题和优化代码至关...

    Spring集成Hibernate写SQLServer

    在Spring集成Hibernate的过程中,我们需要配置Spring的DataSource、SessionFactory以及Hibernate的实体类和映射文件。DataSource是连接数据库的桥梁,SessionFactory则负责创建Session对象,Session对象是执行数据库...

    spring 与hibernate的集成

    通过这种方式,Spring和Hibernate成功集成,使得我们可以利用Spring的IoC和AOP特性来管理事务,同时利用Hibernate进行高效的数据持久化操作。这种集成方式大大提高了代码的可维护性和开发效率,降低了系统的耦合度。

    struts1+spring+hibernate+ibatis集成

    Struts1、Spring、Hibernate和iBatis是Java Web开发中的四大框架,它们共同构建了一个强大的后端架构,用于处理复杂的企业级应用。这个集成方案旨在优化开发流程,提高代码的可维护性和可扩展性。 Struts1是MVC...

    struts2.1.8 集成 spring hibernate需要的 核心 jar

    这个版本的Struts2集成了Spring和Hibernate,使得开发者能够更方便地管理控制层(Controller)和持久层(Persistence Layer)。Spring是一个全面的后端应用框架,而Hibernate则是一个流行的ORM(对象关系映射)工具...

    Spring集成Jpa(Hibernate实现)

    Spring集成JPA(Java Persistence API)是将Spring框架与ORM(Object-Relational Mapping)解决方案之一的Hibernate结合使用的常见实践。这个例子展示了如何在Spring应用中配置和使用JPA,以便利用Hibernate作为JPA...

    spring-hibernate.jar

    spring-hibernate.jar

    spring和hibernate集成Demo

    这篇关于"Spring和Hibernate集成Demo"的内容将深入探讨这两者如何协同工作,以及如何构建一个集成的小型项目。 **Spring框架** Spring的核心是依赖注入(Dependency Injection,DI),它允许开发者通过配置文件或...

    spring-boot 集成hibernate

    在本文中,我们将深入探讨如何将Spring Boot与Hibernate集成,并使用Druid作为数据库连接池。首先,我们需要理解这三个核心组件: 1. **Spring Boot**: 是一个由Pivotal团队提供的开源框架,它简化了创建独立的、...

    非注解Springmvc+spring+hibernate 入门实例

    总的来说,这个入门实例旨在帮助初学者理解如何在没有使用注解的情况下,通过XML配置文件集成SpringMVC、Spring和Hibernate,完成一个简单的Web应用。虽然现在的最佳实践倾向于使用注解和Spring Boot,但理解非注解...

    gwt+spring+hibernate

    标题 "gwt+spring+hibernate" 涉及的是一个使用Google Web Toolkit (GWT)、Spring框架和Hibernate ORM技术的集成示例。这是一个常见的Web应用开发组合,用于构建高效、可扩展且功能丰富的Java web应用程序。下面将...

    Spring与Hibernate集成---声明式事务

    Spring与Hibernate的集成使得开发者可以在一个统一的环境中管理业务逻辑和数据访问,提高开发效率。集成的关键在于Spring的Transaction Management,它提供了声明式和编程式两种事务管理方式。声明式事务管理是通过...

    Webwork+spring+hibernate集成实例

    总的来说,Webwork+Spring+Hibernate的集成为Java开发者提供了一个强大的工具集,用于构建复杂的企业级应用。这种集成方式强调了组件的解耦和职责分离,提高了代码的可测试性和可维护性,同时也提升了开发效率。在...

Global site tag (gtag.js) - Google Analytics