Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java entityManager的范围有多远?_Java_Jpa_Persistence_Java Ee 7 - Fatal编程技术网

Java entityManager的范围有多远?

Java entityManager的范围有多远?,java,jpa,persistence,java-ee-7,Java,Jpa,Persistence,Java Ee 7,假设我有一个无状态会话bean Foo。我已经使用CDI向Foo中注入了EntityManager 我已经了解到,默认情况下,EntityManager将是事务范围的,因此EntityManager的持久性上下文中的任何实体都将由EntityManager管理,直到事务结束 但是如果事务在Foo之外的类Bar中启动呢?所以Foo被注入到Bar中,事务在Bar中启动,然后在该事务中调用Foo。当然,EntityManager不能在创建Foo之前管理对象,但是在Foo中的方法返回之后呢 Foo返回后

假设我有一个无状态会话bean Foo。我已经使用CDI向Foo中注入了EntityManager

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

但是如果事务在Foo之外的类Bar中启动呢?所以Foo被注入到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管理的事务吗?使用“”管理的容器是否需要新的?使用默认边界管理的容器

我建议:


谢谢你的回答。我正在考虑容器管理的事务。因此,默认情况下,容器在Bar中启动一个事务,默认情况下,Foo将该事务连接到Bar中。当Foo返回时,Foo中声明的EntityManager是否仍然有效?它是相同的EM。如果您在相同的TX中,您将获得相同的EM实例。因此,如果你在bean Foo中的方法1()中开始一个TX,Foo在bean Bar中调用方法2(),并且它没有被注释以创建一个新TX(也就是说你继续在同一TX中),那么该实例中注入的EM将是相同的。啊,我是从另一个角度讲的。酒吧叫福。entityManager在Foo中。Foo中的方法结束了,我们回到了酒吧。entityManager(仅在Foo中定义)在Bar中是否仍处于活动状态?我们在同一笔交易中……是的。它仍然是相同的TX,所以它是相同的EM实例。没关系。除非我很好奇为什么这很重要,如果你不把EM注入酒吧,那你为什么会在意呢?因为假设我们在Foo方法完成后回到酒吧。如果我更改了一个由Foo的EntityManager管理的实体,那么按照JPA的工作方式,JPA应该扫描该实体,直到TX结束。但我很好奇这是否会发生,特别是如果Foo现在超出了范围(可能是这样)