HibernateTemplate之模版模式和回调函数
spring中的HibernateTemplate提供了Hibernate DAO模式的支持,通过配置,很容易的就能使用一些常用的功能。此处个人觉得优秀的是模版模式的运用,还有回调函数的使用。看这些优秀框架的源代码实在令人惊叹,非常值得好好学习。废话少说,开始唠叨一些自己的浅见。
要想使用HibernateTemplate,可以extends类HibernateDaoSupport,然后在需要进行持久操作的话,调用getHibernateTemplate().save()|update()|等函数。
下面以例子说明:
public interface DAO{ save();}public DAOImpl extends HibernateDaoSupport implements DAO { public void save() { POJO pojo = new POJO(); pojo.setName("test"); this.getHibernateTemplate().save(pojo); }}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 Object execute(HibernateCallback action) throws DataAccessException {return execute(action, isExposeNativeSession());}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);enableFilters(session);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");disableFilters(session);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());}}}}