jdbcTemplate和hibernateTemplate之二

HibernateTemplate:
在我们dao层使用hibernate时,一种把dao层extends HibernateDaoSupport,
再得到HibernateTemplate,无论调用HiberanteTemplate关于crud数据库时都会调用execute(HibernateCallback(),boolean exposeNativeSession)方法,
我们一般只关心业务,所以只要实现hiberanteCallback方法,在里面实现业务就行了.execute的作用,使用我们不要控制事务,打开session,session.flush,session.close,这些都自动完成.
execute源代码:
public Object execute(HibernateCallback action, boolean exposeNativeSession) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");

Session session = getSession();//得到session
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);//session.flush()保存数据到数据库去
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);//session.close();
}
else {
SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
}
}
}
}

这里最重要的是看flushIfNecessary(session, existingTransaction);这个方法在HiberanteTemplate的父类HiberanteAccessor中:
protected void flushIfNecessary(Session session, boolean existingTransaction) throws HibernateException {
if (getFlushMode() == FLUSH_EAGER || (!existingTransaction && getFlushMode() != FLUSH_NEVER)) {
logger.debug("Eagerly flushing Hibernate session");
session.flush();
}
}

如果我们dao层一个方法中调用,hiberanteTemplate.save(1),hibernateTemplate.save(2).那么,就和jdbcTemplate.update(1),jdbcTemplate(2),一样了,如果同时保存成功或失败.我们也样设置事务.其实原理上面的jdbcTemplate一样.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值