我正在尝试将休眠实体管理器与 mysql 和 glassfish 一起使用。尝试使用 JTA 数据源时出现以下错误:
Caused by: org.hibernate.HibernateException: The chosen transaction strategy requires access to the JTA TransactionManager
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:376)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1367)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:858)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:733)
... 37 more
这是我配置persistence.xml的方式
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="myPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/mysql</jta-data-source>
<class>com.my.shared.entity.MyFile</class>
<class>com.my.shared.entity.MyRole</class>
<class>com.my.shared.entity.MyUser</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show.sql" value="true" />
</properties>
但是,当我配置非 jta 数据源时,它工作正常
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="myPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>jdbc/mysql</non-jta-data-source>
<class>com.my.shared.entity.MyFile</class>
<class>com.my.shared.entity.MyRole</class>
<class>com.my.shared.entity.MyUser</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show.sql" value="true" />
</properties>
</persistence-unit>
</persistence>
这一切都很好,但我真的很想使用:
em.persist(myObject);
代替:
em.getTransaction().begin();
em.persist(myObject);
em.getTransaction().commit();
我是否缺少休眠配置的某些内容,或者甚至可以使用 JTA 数据源?