4

我正在使用 JBoss7 开发基于 JavaEE6 的 Web 应用程序。在我的应用程序中,我将 EntityManager 注入到我的 EJB 中:

class ForumServiceEJB
{
    @PersistenceContext(type=EXTENDED)
    private EntityManager em;

}

class TopicServiceEJB
{
    @PersistenceContext(type=EXTENDED)
    private EntityManager em;

}

当我使用 ForumServiceEJB 的 EntityManager 更新一些数据时出现问题,然后对 DB 进行了更改,但 TopicServiceEJB 的 EntityManager 无法看到这些更改,并且始终从缓存中获取结果。

我使用 ExtendedPerssisteenceContext 因为我的实体包含延迟加载类型的子实体集合。

如何使用/注入 ExtendedPersistenceContext 类型的 EntityManager 并使一个 EJB 中的不同 EntityManager 仍然可以看到其他不同 EJB EntityManager 所做的更改?

我在某处读到 EntityManagers 应该是 RequestScoped 对象。

public class MyEntityManagerProducers {
 @Produces @RequestScoped 
 public EntityManager createDbEm() {
   return Persistence.createEntityManagerFactory("forumDb").
          createEntityManager();
 }

 public void disposeUdEm(@Disposes EntityManager em) {
   em.close();
 }

这是要走的路吗?

4

1 回答 1

1

I am using ExtendedPerssisteenceContext as My Entities contain child Entity Collections of Lazy Loading type.

This is not a good reason to use EXTENDED. I would suggest you to make it default, which is TRANSACTION. And it's good to make your EntityManager request-scoped, or method-scoped, in non-enterprise environment or when using application-managed persistence, as this is not a very heavy object to create. Moreover, neither using application-scoped EntityManager is a good idea, as it is not threadsafe.

Having said that, as you are using JBoss, you should let the container handle the lifecycle of EntityManager, in case you are using JTA. Hence, just inject that with everything default

Note:

Only stateful session beans can have a container-managed, extended entity manager.

Links:

Suggestions:

Your business method should know whether to load the children or not. But that's the ideal case. A number of times we can't say that and completely depends on the user input -- we can't predict that well. Therefore, there are two solutions available,

  1. make a separate AJAX call to load children
  2. Use the filter called open-session-in-view. I would prefer the former.

Links:

于 2012-05-25T03:30:31.270 回答