java – 间接Hibernate / JPA方法调用失去事务
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 间接Hibernate / JPA方法调用失去事务,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1978字,纯文字阅读大概需要3分钟。
内容图文
![java – 间接Hibernate / JPA方法调用失去事务](/upload/InfoBanner/zyjiaocheng/720/64c61d1a0553453aa682fb4170798157.jpg)
我正在使用Spring / JPA2 / hibernate这段代码:
class A {
@Autowired
B b;
@RequestMapping("/test")
public void test(final HttpServletRequest r1, HttpServletResponse r2) throws ... {
b.inner(); // Works
b.outer(); // javax.persistence.TransactionRequiredException:
// no transaction is in progress ... :|
}
@Component
class B {
@PersistenceContext
EntityManager em;
public void outer() { inner(); }
@Transactional
public void inner() { em.flush(); }
}
为什么inner()只在被调用时间接地松散了事务?
解决方法:
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.
Consider the use of AspectJ mode (see mode attribute in table below) if you expect self-invocations to be wrapped with transactions as well. In this case, there will not be a proxy in the first place; instead, the target class will be weaved (that is, its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.
@Autowired引用B b(在A类中)包含一个Spring AOP事务感知代理.
当调用b.inner()时,您在事务感知实例上调用它,并将其标记为@Transactional.因此,启动了Spring托管事务.
当调用b.outer()时,它也在事务感知实例上,但它不是@Transactional.因此,Spring管理的事务未启动.
一旦你进入outer()的调用,对inner()的调用就不会通过事务感知代理,而是直接调用它.它与this.inner()相同.由于您是直接调用它,而不是通过代理调用它,因此它没有Spring事务感知语义.
由于没有启动任何事务,因此会导致TransactionRequiredException.
可能的解决方案包括使方法outer()@Transactional.
@Transactional
public void outer() { inner(); }
或者制作整个班级@Transactional.
@Transactional
@Component
class B {
@PersistenceContext
EntityManager em;
内容总结
以上是互联网集市为您收集整理的java – 间接Hibernate / JPA方法调用失去事务全部内容,希望文章能够帮你解决java – 间接Hibernate / JPA方法调用失去事务所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。