gpt4 book ai didi

java - 一个entityManager的范围能达到多远?

转载 作者:太空宇宙 更新时间:2023-11-04 14:21:02 26 4
gpt4 key购买 nike

假设我有一个无状态 session bean,Foo。我已使用 CDI 将 EntityManager 注入(inject)到 Foo 中。

我读到,默认情况下,EntityManager 将是事务范围的,因此 EntityManager 持久性上下文中的任何实体都将由 EntityManager 管理,直到事务结束。

但是如果事务在 Foo 之外的 Bar 类中开始怎么办?因此 Foo 已被注入(inject)到 Bar 中,事务在 Bar 中启动,然后在该事务中调用 Foo。当然,EntityManager 在 Foo 创建之前无法管理对象,但是 Foo 中的方法返回后呢?

在 Foo 返回后,EntityManager 是否仍在以某种方式管理它在 Foo 中管理的实体,或者即使事务仍在继续,它们在那时是否已分离?如果我在 Foo 中的方法返回后更改 Bar 中实体的值,该更改是否应该传播到数据库?

非常感谢!

编辑:一些代码以使其更清晰

class Bar {

@Inject
Foo foo;

// Transaction starts here
public void doSomething(){
foo.doSomethingElse();

// Transaction is still uncommitted here
// Make a change to an entity here that was in foo's
// entityManager's persistence context
// Does it get picked up and propagated to the db?
// Or is the entityManager gone by this point?
}
// Transaction commits after return of this method
}



@Stateless
class Foo {
@PersistenceContext
EntityManager em;

// This method by default joins the transaction that was already started in Bar
public void doSomethingElse(){
// Do something with entities
}
}

最佳答案

取决于您的事务边界的管理方式。您正在使用 Bean 管理的事务吗?使用 REQUIRES_NEW 管理的容器?使用默认边界管理的容器?

我推荐:

https://docs.oracle.com/javaee/5/tutorial/doc/bncij.html

关于java - 一个entityManager的范围能达到多远?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27197834/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com