javax.persistence.TransactionRequiredException: Executing an update/delete query
mattshma opened this issue · comments
mattshma commented
执行更新的代码如下:
@Transactional
public void saveUser(User user) {
log.debug("Request to save user : {}", user);
String insertStr = "insert into my_user " +
" (name, age) " +
" values (?1, ?2)";
em.createNativeQuery(insertStr)
.setParameter(1, ra.getDepartment())
.setParameter(2, ra.getHiveUser())
.executeUpdate();
}
报错如下:
Exception in xxxImpl.saveUser() with cause = 'NULL' and exception = 'Executing an update/delete query'
javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1496)
修改如下即可:
@Transactional
public void saveUser(User user) {
log.debug("Request to save user : {}", user);
em.getTransaction().begin();
String insertStr = "insert into my_user " +
" (name, age) " +
" values (?1, ?2)";
em.createNativeQuery(insertStr)
.setParameter(1, ra.getDepartment())
.setParameter(2, ra.getHiveUser())
.executeUpdate();
em.getTransaction().commit();
}