javax.persistence.TransactionRequiredException: Executing an update/delete query

使用Spring Data JPA時,使用EntityManager進行原生SQL語句插入,出現javax.persistence.TransactionRequiredException: Executing an update/delete query的異常,使用@javax.transaction.Transactional和@org.springframework.transaction.annotation.Transactional都不行,最後發現可使用以下方法進行事務管理:java

@PersistenceUnit
private EntityManagerFactory    entityManagerFactory;

private void saveByEm(String sql) {


    EntityManager entityManager =entityManagerFactory.createEntityManager();

    Query query = entityManager.createNativeQuery(sql);

    entityManager.getTransaction().begin();

    query.executeUpdate();

    entityManager.getTransaction().commit();

    entityManager.close();

}
複製代碼

參考連接:stackoverflow.com/questions/11016268/why-is-my-transaction-not-active-javax-persistence-transactionrequiredexceptionspring

相關文章
相關標籤/搜索