webyildirim
webyildirim

Reputation: 617

How to get entityManager by using an entity class

How to reach the entity manager which managed the entity. I mean; suppose that i have an entity reference in the sessionBean, how can i get entityManager of this entity belonged one? I had already tried (plz see getEntityManagerOfEntity() method) contains method of em; but it does not work.

Thx bgrds

@Stateless(name = "MainManager", mappedName = "MainManager")
@TransactionManagement(TransactionManagementType.CONTAINER)
@Interceptors(value = { PerformanceMonitor.class, ProfileInterceptor.class })
public class MainManagerBean implements MainManager, MainManagerLocal
{
    private Logger logger = Logger.getLogger(this.getClass());

    @PersistenceContext(unitName = "DSApp")
    private EntityManager manager;

    @PersistenceContext(unitName = "DSIX")
    private EntityManager integrationManager;

    @Resource
    SessionContext ctx;



public EntityManager getEntityManagerOfEntity(SuperEntity superEntity)
{
    if (manager.contains(superEntity))
        return manager;
    else if (integrationManager.contains(superEntity))
        return integrationManager;

    return null;
}



public SuperEntity findByPrimaryKey(SuperEntity superEntity)
{
    getEntityManagerOfEntity(superEntity).setFlushMode(FlushModeType.COMMIT);
    return dao.findByPrimaryKey(getEntityManagerOfEntity(superEntity), superEntity);

Upvotes: 2

Views: 1278

Answers (1)

kostja
kostja

Reputation: 61578

You cannot backtrack the EntityManager from an entity using the JPA API, even when it is still managed.

What you can do, if you have references to different EMs in your bean and the entity is managed, is to check the right EM by calling em.contains(entity).

In most cases it is not really important to know, which EM has fetched an entity originally, since you can merge the entity into any persistence context and continue working with it.

Upvotes: 2

Related Questions