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。

版权声明:著作权归作者所有。

相关推荐

解决Spring session报错JedisDataException: ERR unknown command 'CONFIG'

在线上部署服务时,spring-session报了一个redis的错误,如下:redis.clients.jedis.exceptions.JedisDataException: ERR unknown command 'CONFIG'原因是spring-session调用了CONFIG命令来配置Keyspace notifications功能。而线上环境的redis基于权限的考虑,禁止应用服务执

Spring Boot,Spring Data配置多数据源DataSource

这里已配置Oracle和PostgreSQL为例。application.properties配置多数据源# Oracle DB - "foo"spring.datasource.url=jdbc:oracle:thin:@//db-server-foo:1521/FOOspring.datasource.username=fooadminspring.datasource.password=fo

Spring Boot集成kafka

Spring Boot对kafka提供了自动配置(auto configuration)。使用用Spring Boot只需要做很少的配置即可集成对kafka的访问。pom配置1、继承spring-boot-starter-parent<parent>   <groupId>org.springframework.boot&l