我有一個實用程序類,如下所示。我希望能夠將此類與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