org.hibernate.HibernateException: The chosen transaction strategy requires access to the JTA TransactionManager
at org.hibernate.impl.SessionFactoryImpl.(SessionFactoryImpl.java:329)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1294)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:915)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:730)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:127)
這個錯誤消息是有意義的。persistence.xml的配置沒有指定事務類型。容器環境中默認的事務類型是JTA。當未將它被告知Weblogic Server的事務管理器的信息時,Hibernate會有所抱怨。配置Hibernate使之明確使用本地事務怎么樣?我編輯了persistence.xml
<persistence-unit name="test" transaction-type="RESOURCE_LOCAL"> 然后再次運行構建腳本,它將部署并運行JUnit測試,
$ ant -Dprovider=hibernate 讓我驚喜的是,這次部署的應用程序沒有出錯。但是測試沒有成功。
[echo] Running JUnit Test: junit.TestJPAService ...
[junit] Logical Persistence Provider is [hibernate]
[junit] Actual Persistence Provider is [org.hibernate.impl.SessionImpl]
[junit] Test junit.TestJPAService FAILED
[echo] *** ERROR: There are test failures. Output is shown below
[concat] Testsuite: junit.TestJPAService
[concat] Tests run: 2, Failures: 1, Errors: 0, Time elapsed: 2.934 sec
[concat]
[concat] ------------- Standard Output ---------------
[concat] Contacting server t3://localhost:7001 as weblogic for JPAService
[concat] ------------- ---------------- ---------------
[concat] ------------- Standard Error -----------------
[concat] Logical Persistence Provider is [hibernate]
[concat] Actual Persistence Provider is [org.hibernate.impl.SessionImpl]
[concat] ------------- ---------------- ---------------
[concat] Testcase: testLog(junit.TestJPAService): FAILED
[concat] Message is not assigned any identifier
[concat] junit.framework.AssertionFailedError: Message is not assigned any identifier
[concat] at junit.TestJPAService.testLog(Unknown Source)
通過了一個測試。用org.hibernate.impl.SessionImpl,確切地說,是它的代理對這個bean進行了注入。
但是,為什么向 Message實例分配標識符沒有成功?
這只不過因為我們設計bean使用容器管理事務,而現在卻配置為使用本地事務。所以我們的bean代碼和容器都沒有提交事務,而且因為標識值指定為由提供者賦值(見Message.java中的@Id注釋)并且由Hibernate利用數據庫列的自動增量特性為標識賦值――所以也沒有提交表示沒有標識值賦值。
當然,我們能夠在JPAServiceBean.log()方法中添加明確的事務分界;但這不是解決方案。在容器環境中,我們傾向于使用容器管理的事務,傾向于配置持久性單元使用JTA。
如何告知Hibernate使用Weblogic事務管理器并將它的事務與容器事務結合起來?我通過Google進行了幾分鐘的搜索找到了答案。向persistence.xml添加以下屬性。
文章來源于領測軟件測試網 http://www.kjueaiud.com/