@Modifying注解与Can not issue data manipulation statements with executeQuery().

本文记录了在使用Spring Data JPA时遇到的更新和删除操作错误,详细描述了从报错信息到问题解决的整个过程。首先,尝试使用@Query进行更新操作导致SQL错误,接着添加@Modifying注解后出现事务错误,最终通过添加@Transactional解决了问题。总结得出,在JPA中执行修改和删除操作需同时使用@Modifying和@Transactional注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我是在使用Spring Data jpa中遇到这个问题的
具体报错如下

#[admin-DESKTOP-7MF0MCO.log]# 2021-09-10 18:01:49 WARN [http-nio-8080-exec-3] org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: S1009
#[admin-DESKTOP-7MF0MCO.log]# 2021-09-10 18:01:49 ERROR [http-nio-8080-exec-3] org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Can not issue data manipulation statements with executeQuery().
#[admin-DESKTOP-7MF0MCO.log]# 2021-09-10 18:01:49 ERROR [http-nio-8080-exec-3] org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.22.jar:8.0.22]
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.22.jar:8.0.22]

我的代码如下
业务层实现类

@Override
    public ResponseResult<String> delete(Long id){
        transRepository.updateByTransId(id);
        return new ResponseResult<String>().setSuccessData(null);
    }

持久层

@Query(nativeQuery = true, value = " update imp_config_trans set status = '0' , del_flag = '1' where id = ?")
void updateByTransId(Long id);

经过百度,发现,@Query已经不能适用于修改、删除操作了,
于是我加入了@Modifying,如下

@Modifying
@Query(nativeQuery = true, value = " update imp_config_trans set status = '0' , del_flag = '1' where id = ?")
void updateByTransId(Long id);

结果报事务错,

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

于是加入@Transactional注解

@Modifying
@Transactional
@Query(nativeQuery = true, value = " update imp_config_trans set status = '0' , del_flag = '1' where id = ?")
void updateByTransId(Long id);

成功

总结:在jpa操作中,修改与删除操作不能只写@Query,还应加上
@Modifying
@Transactional

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值