码迷,mamicode.com
首页 > Web开发 > 详细

hibernateTemplate中的回调函数

时间:2016-11-20 19:29:35      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:close   数据库   template   man   自己实现   exce   ogg   接口   isa   

hibernateTemplate中的回调函数:可以发现在hibernateTemplate类中所有对数据库的操作实现都是利用的回调函数
hibernateTemplate中回调函数源码:

public <T> T execute(HibernateCallback<T> action) throws DataAccessException {
return doExecute(action, false);

}

public <T> T executeWithNativeSession(HibernateCallback<T> action) {
return doExecute(action, true);
}


分析: 回调函理解:在execute或executeWithNativeSession中调用 doExecute方法并将action当成参数传递,而在doExecute方法中调用action中的方法
参数 HibernateCallback<T> 是接口 里面只有一个doInHibernate(Session session)方法,在使用的时候可以通过创建匿名内部类的形式实现里面doInHibernate(Session session)此方法中实现具体的逻辑

doExecute方法中调用函数HibernateCallback中的doInhibernate(Session session) 方法,此方法的作用是:得到一个session并将它传入doInhibernate方法中 返回的是 return action.doInHibernate(sessionToExpose);将自己实现的类中的doInHibernate方法中的返回值返回

方法 execute executeWithNativeSession 的区别:
execute 方法 使用的是 session代理 executeWithNativeSession 使用的是本机session
public interface HibernateCallback<T> {
T doInHibernate(Session session) throws HibernateException;
}

protected <T> T doExecute(HibernateCallback<T> action, boolean enforceNativeSession) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");

Session session = null;
boolean isNew = false;
try {
session = getSessionFactory().getCurrentSession();
}
catch (HibernateException ex) {
logger.debug("Could not retrieve pre-bound Hibernate session", ex);
}
if (session == null) {
session = getSessionFactory().openSession();
session.setFlushMode(FlushMode.MANUAL);
isNew = true;
}

try {
enableFilters(session);
Session sessionToExpose =
(enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session));
return action.doInHibernate(sessionToExpose);
}
catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
}
catch (RuntimeException ex) {
// Callback code threw application exception...
throw ex;
}
finally {
if (isNew) {
SessionFactoryUtils.closeSession(session);
}
else {
disableFilters(session);
}
}
}

hibernateTemplate中的回调函数

标签:close   数据库   template   man   自己实现   exce   ogg   接口   isa   

原文地址:http://www.cnblogs.com/javalu/p/6082992.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!