Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell if my EntityManager is using JTA or RESOURCE_LOCAL datasource?

I have a utility class as shown below. I want to be able to use this class with either RESOURCE_LOCAL or JTA persistence units. If I change the persistence.xml from JTA to RESOURCE_LOCAL I shouldn't have to change the code.

I tried using EntityManager.getTransaction() to see if there is an active transaction, but the call to getTransaction() throws an Exception if JTA is being used. I could surround the call to getTransaction() with a try/catch but I don't want to resort to Exception handling for this. The EntityManager.getProperties() don't show anything that indicates JTA or RESOURCE_LOCAL

I need some way to tell what type of persistence unit the EntityManager (or EntityManagerFactory) is using in the code below.

public class CredentialsUtil {

public static final String VGBD_PU = "VGDBpu";
static Logger logger = Logger.getLogger(CredentialsUtilStatic.class);
static EntityManagerFactory emf = Persistence.createEntityManagerFactory(VGBD_PU);
public static final String sharedKey="pgpsympwd";



public static String getPassword(String username) {

    String selectStr = "select pgp_sym_decrypt(pgpsympassword, '" + sharedKey + "') from credentials where username='" + username + "'";

    EntityManager em =null;
    String password = "";

    try {
        em = emf.createEntityManager();

        java.util.Map<java.lang.String,java.lang.Object> propMap = em.getProperties();
        logger.info(propMap.keySet().size() + " properties");

        for (String key : propMap.keySet())
            logger.info(key + ", " + propMap.get(key));

        EntityTransaction tx = em.getTransaction(); ...
like image 487
Dean Schulze Avatar asked Nov 04 '22 11:11

Dean Schulze


1 Answers

You can try something like this, which relies on the different APIs for transactions for the two entity manager types:

public boolean isResourceLocal(EntityManager em) {

  try {
    EntityTransaction tx = em.getTransaction();
    return true;
  } catch (IllegalStateException ex) {
    return false;
  }

}
like image 131
Jeff Putney Avatar answered Nov 16 '22 17:11

Jeff Putney