【问题标题】:What is the scope of a Transaction used in shared EntityManager contexts?共享 EntityManager 上下文中使用的事务的范围是什么?
【发布时间】:2015-07-29 15:49:53
【问题描述】:

在 JPA 中: 考虑以下示例,该示例使用容器管理的事务范围实体管理器。

public class ItemDAOImpl implements ItemDAO { 
    @PersistenceContext(unitName="ItemService") 
    EntityManager em; 

    LoggingService ls; 

    public void createItem(Item item) { 
        em.persist(item); 
        ls.log(item.getId(), "created item"); 
    } 

    // ... 
}  

public class LoggingService implements AuditService { 
    @PersistenceContext(unitName="ItemService") 
    EntityManager em; 
    
 
    public void log(int itemId, String action) { 
        // verify item id is valid 
        if (em.find(Item.class, itemId) == null) { 
            throw new IllegalArgumentException("Unknown item id"); 
        } 
        LogRecord lr = new LogRecord(itemId, action); 
        em.persist(lr); 
    } 

} 

我是否正确地假设 ls.log() 方法
将使用调用方法的事务。
我现在对这些事情很困惑,你能帮忙吗?

【问题讨论】:

    标签: java jpa persistence


    【解决方案1】:

    如果您在 EJB 中,那么很可能这些方法将使用相同的事务,因为 default transaction propagation 方法。只需检查它们是如何配置的,因为它们似乎是在 XML 文件中配置的。

    【讨论】:

    • 如果它们是 EJB 方法中使用的类怎么办?
    • 那么它取决于谁以及如何注入EntityManager 实例。您可以检查它是否是同一个事务:在一种方法中持久化和刷新新实体并在另一种方法中抛出异常。结果应该是,没有任何东西被持久化。
    • 我还有一个问题,REQUIRED 行为是否意味着在尚不存在交易的情况下,将创建一个新交易?
    • 是的,正如你所说。详细信息在这里给每个TransactionAttributeType :)
    猜你喜欢
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    相关资源
    最近更新 更多