1.什么是模版方法
模板方法的定义是:定义一个操作中的算法骨架,而将一些步骤延迟到子类中。
这是一个标准的模版方法实现,当然也有一些变体,spring中用到的模版方法就进行了变体。
2.HibernateTemplate中的模版方法应用
我们知道,对hibernate操作有一些基本步骤:
1.读取并解析映射信息,创建SessionFactory
2.打开Sesssion
3.创建事务Transation
4.持久化操作
5.提交事务
6.关闭Session
7.关闭SesstionFactory
如果你要书写多个数据库操作方法,每个方法中必须有以上的七个步骤,这样将会产生大量的重复代码。那么,有没有办法重用一些逻辑呢。
我们发现,其中1,2,3,5,6,7步骤都是相同的,唯有4步骤是变化的。因此可以考虑使用我们前面提到的模版方法,定义一个操作中的算法骨架,而将一些步骤延迟到子类中。挺符合我们现在的场景,哈哈。当然spring并没有采用子类的方式来实现,而是采用了回调的方式实现,将变化部分很好的抽象出来。实现了重用逻辑的效果。
下面来看HibernateTemplate中是如何应用模版方法的
public <T> T executeWithNativeSession(HibernateCallback<T> action) {
return doExecute(action, false, true);
}
public interface HibernateCallback<T> {
T doInHibernate(Session session) throws HibernateException,
SQLException;
}
protected <T> T doExecute(HibernateCallback<T> action,
boolean enforceNewSession, boolean enforceNativeSession)
throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Session session = (enforceNewSession ? SessionFactoryUtils
.getNewSession(getSessionFactory(), getEntityInterceptor())
: getSession());
boolean existingTransaction = (!enforceNewSession && (!isAllowCreate() || 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 = (enforceNativeSession
|| isExposeNativeSession() ? session
: createSessionProxy(session));
// 回调
T 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());
}
}
}
}
public List find(final String queryString, final Object... values)
throws DataAccessException {
return executeWithNativeSession(new HibernateCallback<List>() {
public List doInHibernate(Session session)
throws HibernateException {
Query queryObject = session.createQuery(queryString);
prepareQuery(queryObject);
if (values != null) {
for (int i = 0; i < values.length; i++) {
queryObject.setParameter(i, values[i]);
}
}
return queryObject.list();
}
});
}
在get方法中,采用了匿名对象的方式实现了HibernateCallback这个借口,将此对象作为参数传递给executeWithNativeSession方法,
接着传给doExecute方法,doExecute中回调了,HibernateCallback中的doInHibernate方法,T result = action.doInHibernate(sessionToExpose);
spring将具体的数据库操作通过接口的方式抽象出来,并在模版方法中回调此借口的方法,实现了逻辑的重用。
3.总结
可见,模版方法的核心思想是实现算法的框架,将一些变化步骤进行抽象,放到另外的地方实现。以上纯属个人理解,如有误区,还望指证。