JTA EntityManager无法使用getTransaction()

时间:2017-06-20 14:23:31

标签: java jpa jta

我有一个java应用程序,我需要连接到wildfly 10.1中的两个数据源。 我已经配置了数据源并且已成功连接。 但我无法插入或更新数据,因为它给出了以下异常

 A JTA EntityManager cannot use getTransaction()

这是我的persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
    <persistence-unit name="MysqlDatabase"
        transaction-type="JTA">

        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>java:/MySqlDS</jta-data-source>
        <class>com.mysql.model.Test</class>
        <!-- <shared-cache-element>ENABLE_SELECTIVE</shared-cache-element> -->
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" />
            <property name="javax.persistence.jdbc.user" value="abc" />
            <property name="javax.persistence.jdbc.password" value="xyz" />
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="hibernate.hbm2ddl.auto" value="create" />
            <!-- Configuring Connection Pool -->

        </properties>
    </persistence-unit>
</persistence>

这是我的代码

public class TestDao extends MysqlDao implements Serializable,TestInterface{
    EntityManager em = null;
    public void addobj(Test test){
        try{
        em=getEm();
        em.getTransaction().begin();
        em.persist(test);
        em.getTransaction().commit();
        }catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
        }

    }

我从以下课程获得实体经理

    private static EntityManagerFactory emf = Persistence
            .createEntityManagerFactory("MysqlDatabase");

    public static EntityManagerFactory getEmf() {
        return emf;
    }

    public static EntityManager getEm() {

//      LOG.debug(emf);
        System.out.println(getEmf());
        EntityManager em = getEmf().createEntityManager();
        System.out.println("Entity Manager"+em);
//      LOG.debug("Initialising EntityManager ... ");
        return em;
    }

我已尝试过以下链接中提供的建议 Error: A JTA EntityManager cannot use getTransaction()

Error: A JTA EntityManager cannot use getTransaction()

没有什么对我有用

请告诉我如何解决此问题。

0 个答案:

没有答案