java – 间接Hibernate / JPA方法调用失去事务

weixin_38092995 2019-09-12 11:16:10
我正在使用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()只在被调用时间接地松散了事务?
...全文
11 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38095754 2019-09-12
  • 打赏
  • 举报
回复
http://static.springsource.org/spring/docs/current/reference/transaction.html#transaction-declarative-annotations 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;

433

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧