[英]Getting rid of “No Hibernate Session bound to thread” and performances with @Transactional on read methods
I've introduced HibernateTransactionManager in my project, because we need to use transactions for some service methods. 我在项目中引入了HibernateTransactionManager,因为我们需要对某些服务方法使用事务。 I've also followed the best practice to inject the SessionFactory into the DAO layer instead of implementing the HibernateDaoSupport.
我还遵循了将SessionFactory注入DAO层的最佳实践,而不是实现HibernateDaoSupport。
Now in some read methods that are not annotated with @Transactional I got the error: 现在,在一些未使用@Transactional注释的读取方法中,出现了错误:
No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
I know how to solve it, just add the @Transactional all over the place. 我知道如何解决,只需在整个地方添加@Transactional。 But my colleagues are worried about performance.
但是我的同事担心性能。 Should also read methods like:
还应该阅读如下方法:
return sessionFactory.getCurrentSession().createCriteria(MyClass.class).add(Restrictions.eq("color", color)).addOrder(Order.asc("createDate")).list();
be annotated with @Transactional? 被@Transactional注解?
I've also read this post Some clarification about Spring @Transactional annotation on a method that discourage to use this annotation in DAO layer, so I don't see what is the best practice for getting rid of the issue AND have good performances on read methods . 我还阅读了这篇文章,该文章对不鼓励在DAO层中使用此注解的方法进行了有关Spring @Transactional注解的澄清 ,因此,我看不出消除该问题的最佳实践是什么,并且在阅读时表现出色方法 。
Many thanks for helping! 非常感谢您的帮助!
When you use the Spring TransactionManager abstraction, you must always mark all Service methods with: 使用Spring TransactionManager抽象时,必须始终使用以下标记所有Service方法:
@Transactional
@Transaction(readOnly = true)
for read-only methods @Transaction(readOnly = true)
用于只读方法 That's because Hibernate will no longer manage transaction, but instead it will delegate this responsibility to the Spring framework. 这是因为Hibernate将不再管理事务,而是将这种责任委托给Spring框架。 Unless you mark each transaction-boundary method with the
@Transactional
annotation, Spring cannot associate the current Thread with a Hibernate Session and an associated JDBC Connection. 除非使用
@Transactional
批注标记每个事务边界方法,否则Spring无法将当前线程与Hibernate Session和关联的JDBC Connection关联。
So, using @Transactional
is not an option. 因此,不能使用
@Transactional
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.