我是在使用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