我有一个实用程序类,如下所示。我希望能够将此类与RESOURCE_LOCAL或JTA持久性单元一起使用。如果我将JTA中的persistence.xml更改为RESOURCE_LOCAL,则不必更改代码。如何判断我的EntityManager是否使用JTA或RESOURCE_LOCAL数据源?
我尝试使用EntityManager.getTransaction()来查看是否存在活动事务,但如果正在使用JTA,getTransaction()的调用将引发异常。我可以用try/catch来包围getTransaction()的调用,但我不想诉诸异常处理。 EntityManager.getProperties()不显示任何指示JTA或RESOURCE_LOCAL的东西
我需要一些方法来告诉EntityManager(或EntityManagerFactory)在下面的代码中使用何种类型的持久性单元。
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(); ...
这将导致JTA回滚... – dmatej
由于JPA 2.1您可以使用em.isJoinedTransaction() – dmatej