简体   繁体   中英

How to detect the type of a transaction: JTA or Resource Local from java code?

Is it possible to detect the type of a transaction (JTA or Resource Local) in Bean Managed Transaction using EclipseLink? If yes, how can this be done?

Actually i need to detect the transaction type and the JNDI name aswell if possible in java class.

You can detect the type of transaction as follows;

EntityManager em = emf.createEntityManager();

boolean isJta = false;
try {
    EntityTransaction et = em.getTransaction();
} catch (IllegalStateException ise) {
    if (ise.getMessage().startsWith("A JTA EntityManager cannot use getTransaction")) {
        isJta = true;
    }
}

You might have to tweak the error message: this one matches what Hibernate (4.x) throws, EclipseLink probably throws a slightly different message (although probably the same exception class instance).

As for the JNDI name of the data source or persistence unit, that type of information, AFAIK, is not exposed by the JPA classes. You might be able to extract it by using EclipseLink (or for other ORM frameworks, ORM-framework-specific) methods. In other words, the EntityManagerFactory instance is of course an instance of an EclipseLink class that implements that interface. I would debug a test where you have an instance of the EMF and look through it's fields and properties.

Otherwise, you might be able to scan the JNDI catalog and pick out the right one, for example see the code here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM