发布于 4个月前

Spring JPA报错:InvalidDataAccessApiUsageException: Executing an update/delete query

集成Spring JPA,在执行delete,update时需要添加事务。

错误信息:

org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:402)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)

解决:通过添加注解@Transactional

@Transactional
@Modifying
@Query(value = "update User user set user.address = :address where user.id = :id ")
void updateUserAddress(@Param("id") int id,@Param("address") String address);

注意,添加的是import org.springframework.transaction.annotation.Transactional。

©2020 edoou.com   京ICP备16001874号-3