问题描述
这是大多数DAO中使用的典型设置:
This is a typical setup used in most DAO:
@Transactional
@Repository
public class DAO {
@Autowired
SessionFactory sessionFactory;
public void save(Entity o) {
sessionFactory.getCurrentSession().save(o);
}
public Entity load(int id) {
return (Entity)sessionFactory.getCurrentSession().get(Entity.class, id);
}
}
我只看到getCurrentSession()
被呼叫,没有openSession
或close
.
I see only getCurrentSession()
called, no openSession
or close
.
因此,当我从load
返回实体时,它不在会话中,因此无法加载惰性集合.同样,保存似乎总是刷新!
So when I return the entity from load
it's not in session, lazy collections cant be loaded. Similarily, save seems to always flush!
Spring的@Transactional
注释是否本身就具有打开和关闭会话以及交易的魔力?
Does the @Transactional
annotation from spring do the magic of opening and closing sessions AND transactions all by itself?
推荐答案
在Spring中,由@Transactional
划分的业务交易与休眠的Session
之间存在一一对应的关系.
In Spring, there is a one-to-one correspondence between the business transaction demarcated by @Transactional
, and the hibernate Session
.
也就是说,当通过调用@Transactional
方法开始业务交易时,将创建休眠会话(TransactionManager可能将实际创建延迟到首次使用该会话之前).该方法完成后,将提交或回滚业务事务,这将关闭休眠会话.
That is, when a business transaction is begun by invoking a @Transactional
method, the hibernate session is created (a TransactionManager may delay the actual creation until the session is first used). Once that method completes, the business transaction is committed or rolled back, which closes the hibernate session.
在您的情况下,这意味着调用DAO方法将开始一个新的事务(除非事务已在进行中),退出DAO方法将结束它,这将关闭休眠会话,并刷新它,并提交或回滚相应的休眠事务,该事务随后又提交或回滚相应的JDBC事务.
In your case, this means that invoking a DAO method will begin a new transaction (unless a transaction is already in progress), and exiting the DAO method will end it, which closes the hibernate session, which also flushes it, and commits or rolls back the corresponding hibernate transaction, which in turn commits or rolls back the corresponding JDBC transaction.
由于这是典型用法,因此hibernate文档将其称为会话每次操作反模式.同样,春季参考手册中所有@Transactional
的示例都放在业务服务方法(或类)上,而不是存储库上.
As for this being typical use, the hibernate documentation calls this the session-per-operation anti pattern. Likewise, all examples of @Transactional
in the spring reference manual are put on business service methods (or classes), not repositories.
这篇关于@Transactional如何影响Hibernate中的当前会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!