2017-06-29 65 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); 
}