2017-06-29 60 views
0

我面临一个问题,不知道什么是错的。该cenary:休眠5 +非JTA数据源:对象未被存储

  • 休眠5
  • 的Apache Tomcat 9
  • JSF 2

没有春天。说出来很重要,因为我发现这个问题是在Spring使用中发生的,但这不是我的情况。

在Tomcat上正确配置了数据源,并且Hibernate还为每个新实体正确创建了表并更新了schemma。

问题是当我尝试坚持一个新的实体时,什么也没有发生。然后我试图包括“冲洗()”呼......但后来我有一个错误,说我没有交易活跃:

javax.persistence.TransactionRequiredException:没有交易正在进行

这似乎是与交易相关的要求的问题,但我自己也尝试:

  • 包括法“@Transactional”注解;
  • 包含类的“@Transactional”注释;
  • 强制开始事务与“beginTransaction()”调用,但后来我有一个空指针;

所以......我不知道该怎么做。

你会看到我的相关代码。你能帮我解决这个问题吗?

persistence.xml文件:

<persistence-unit name="hospitalPU" transaction-type="RESOURCE_LOCAL"> <description> Persistence unit for Hibernate </description> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <non-jta-data-source>java:comp/env/jdbc/hospitalDatasource</non-jta-data-source> <properties> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.hbm2ddl.auto" value="update" /> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" /> <property name="hibernate.format_sql" value="true" /> <property name="hibernate.default_catalog" value="hospital" /> <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/hospitalDatasource"/> <property name="hibernate.id.new_generator_mappings" value="false" /> </properties> </persistence-unit>

我的实体:

@Entity(name="Dominio") 
@Table(name="Dominio") 
public class Dominio implements Serializable{ 

private static final long serialVersionUID = 1L; 

@Id 
@GeneratedValue 
private Integer id; 

here goes another fileds and getters/setters... 

在我管理的bean,我有:

@PersistenceUnit 
private EntityManagerFactory emf; 

兼:

protected synchronized EntityManager getEntityManager() { 
    if (emf == null) { 
     emf = Persistence.createEntityManagerFactory("hospitalPU"); 
    } 
    return emf.createEntityManager(); 
} 

这似乎很好地工作,但问题发生在这里:

有了这个,没有发生,没有异常occours。只是什么也没有发生:

getEntityManager().persist(getDominio()); 

有了这个,我有 “javax.persistence.TransactionRequiredException:没有交易正在进行”:

getEntityManager().persist(getDominio()); 
getEntityManager().flush(); //exception occours here! 

我在做什么错?在此先感谢大家!

回答

0
+0

好的,感谢您的回复@Mayank。 但没有为我工作。我已经按照这个推荐,并得到了同样的错误: https://gist.github.com/imanoleizaguirre/3819393 第二和第三个链接不适用于我的情况,因为它指的是使用Spring或旧版本的JPA /休眠。 还是谢谢! –

0

这里这一次清楚地说明是什么问题: “javax.persistence.TransactionRequiredException:没有交易正在进行中”

第一,您已经明确提到您正在使用非JTA数据源。这意味着容器将不再为您处理交易界限。您必须自己开始并提交/回滚事务。因此,您需要遵循以下内容:

EntityManager em = .... 
EntityTransaction et = em.getTransaction(); 
try { 
    et.begin(); 
    em.persist(entity); 
    et.commit(); 
} catch (Exception ex) { 
    et.rollback(); 
    throw new RuntimeException(ex); 
}