Search code examples
javajpapersistence

What is the scope of a Transaction used in shared EntityManager contexts?


In JPA: consider the following example, which uses a Container managed transaction scoped Entity manager.

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); 
    } 

} 

Am I right in supposing that ls.log() method
will use the transaction of the calling method.
I'm pretty confused about these things right now, can you help?


Solution

  • If you are in EJBs, then very probably those methods will use the same transaction, because of the default transaction propagation method. Just check how they are configured, as it seems they are configured in an XML file.