簡體   English   中英

JBoss WildFly上具有JPA 2.1和JTA的動態數據源

[英]Dynamic Datasources with JPA 2.1 and JTA on JBoss WildFly

我對JPA和JTA的Jboss WildFly9感到生氣。 在我的項目需求中,我必須實現多租戶,因此必須在persistence.xml中動態更改數據源。

使用jee方法不可能,因此有人建議我使用經典方法:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("idelivery"); 
EntityManager em = emf.createEntityManager();

因此,到現在為止,我可以自己創建enetitymanager,也可以在哈希圖中(包括數據源)設置jpa屬性。

現在我想至少使用JTA使用事務管理器來處理事務。

這些是我通過代碼設置的屬性:

Properties properties = new Properties(); 
properties.put ("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
properties.put("javax.persistence.provider", "org.hibernate.jpa.HibernatePersistenceProvider"); 
properties.put("javax.persistence.transactionType", "JTA");
properties.put("javax.persistence.jtaDataSource", dataSourcePath); 

事務類型現在是JTA。 所以我希望我可以使用一些代碼,例如:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("idelivery"); 
EntityManager em = emf.createEntityManager();
MyEntity exUser= new MyEntity();
try{
Context context = new InitialContext();
UserTransaction userTransaction = (UserTransaction)context.lookup("java:comp/UserTransaction");
userTransaction.begin();
em.persist(exUser);
userTransaction.commit();

當然,由於Hibernate引發了異常,因此這段代碼根本不起作用:

java.lang.NullPointerException at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus()

告訴我在創建實體管理器時無法加入事務。

那么...我該如何尊重我的項目要求...使用動態數據源創建自己的持久性並同時使用事務管理器?

Hibernate具有自己的多租戶解決方案。 這不是JPA標准的一部分,但是與它兼容並且在很大程度上正交。

它與托管持久性單元一起使用,並且與JTA兼容。

我已經在WildFly 8.2.0.Final和9.0.1.Final上成功使用了SCHEMA策略。

您只需要實現兩個幫助器類,然后在persistence.xml對其進行配置。

如果可以事先告訴您需要多少數據源,那么可以使用CDI生產者模式對實體管理器進行某種上下文選擇。

在persistence.xml中定義所有可能的數據源,然后使用某種生產者單例工廠類根據其持久性單元將其注入。

創建一個生產者方法,該方法根據您當前的上下文選擇正確的實體管理器。

然后在您的ejb或cdi bean中,通過CDI注入獲得一個entitymanager實例

@Inject私有EntityManager em

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM