【问题标题】:Extended Persistence Context with ViewScoped CDI beans使用 ViewScoped CDI bean 的扩展持久性上下文
【发布时间】:2016-05-02 08:03:45
【问题描述】:

我是 Seam 的老用户,现在正尝试迁移到 Java EE7、JSF2.2 和 CDI。 在 Seam 中,您大多数时候倾向于使用具有扩展范围的 EntityManager(在 Seam 对话范围中)。你没有得到任何关于 Ajax 请求等的 LIE。

我正在尝试以与 Java EE7 和 CDI 类似的方式执行此操作,但不知何故注入的 EntityManager 只是事务范围。当我在之前加载的实体中收到 ajax 请求时不再管理。

我在我的 CDI bean 上使用新的 javax.faces.view.ViewScoped 和 javax.transactional.Transactional。

我的制作人:

 @PersistenceContext(unitName = "primary", type = PersistenceContextType.EXTENDED)
    private EntityManager entityManager;

    @Produces
    @Default
    @Dependent
    public EntityManager getEntityManager() {
        return entityManager;
    }

还有我的 CDI bean:

@Named
@ViewScoped
@Transactional
public class TestBean implements Serializable{
/**
     * 
     */
    private static final long serialVersionUID = 1L;


    @Inject
    EntityManager entityManager;

    Logger log =  Logger.getLogger(TestBean.class);

    private TestEntity lastTest = null;

    public void testAdd(){
        TestEntity test = new TestEntity();
        test.setVal("Test "+System.currentTimeMillis());
        entityManager.persist(test);
        entityManager.flush();
        log.infov("Created test entity {0}", test);
        lastTest = test;
    }

    public void testRead(){
        List<TestEntity> test = entityManager.createQuery("select t from TestEntity t").getResultList();
        for(TestEntity t: test){
            log.infov("Found {0} managed {1}",t,entityManager.contains(t));
        }
        if(lastTest!=null){
            log.infov("Last Test {0} managed {1}",lastTest,entityManager.contains(lastTest));
        }
    }

所以当我第一次通过 Ajax 调用 testAdd() 时,它会创建一个新的测试实体。然后当我调用 testRead() 时,它会获取所有测试实体并检查最后创建的测试实体是否仍在管理(如果它是具有扩展持久上下文的 EntityManager 则应该这样做)。但是 entityManager.contains(lastTest) 总是返回 false。

我做错了什么?

我相信我不能直接在 CDI bean 中使用 @PersistenceContext。那么我如何获得所需的(Seam like)行为?

【问题讨论】:

  • 您的生产者是 CDI bean 还是 EJB?
  • 生产者是 CDI bean。从来没有想过在 EJB 中做生产者。我想这可能行得通。会尝试
  • Deltaspike 对来自 Seam 的 Java EE 7 初学者有很大帮助。您应该按照deltaspike.apache.org/documentation/… 的建议尝试 RequestScoped 持久性上下文

标签: jpa cdi seam java-ee-7


【解决方案1】:

当您指定注入的 EntityManager 是扩展的持久性上下文时,所有对象实例都保持托管状态。扩展的持久性上下文只能在有状态会话 bean 中使用。

这是根据 JBOSS 文档:https://docs.jboss.org/ejb3/app-server/tutorial/extended_pc/extended.html

考虑将您的插入/更新/删除操作打包到 EJB 中,而从数据库中简单读取可以通过 CDI bean。但是涉及到多次读写以及事务的更复杂的操作应该在 EJB 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 2013-03-12
    • 2012-07-19
    • 2015-02-07
    相关资源
    最近更新 更多