java原生SQL @Query进行插入操作出错,java.sql.SQLException: Can not issue data manipulation statements with executeQuery().

java原生SQL @Query进行插入操作出错,java.sql.SQLException: Can not issue data manipulation statements with executeQuery().

——墨问苍生


 

在做一个接口的时候,数据库插入出现错误

关键代码如下:

1 public interface IStaffDao extends JpaRepository<Staff,Integer> {
2     @Query(value="insert into role_persons(role_id,persons_id) values(?1,?2)",nativeQuery=true)
3     int insertRolePerson(long role_id,long persons_id);
4 }

后续百度查找资料后发现是缺少了

@Modifying注解

这个注解是通知jpa,这是一个update或者delete操作,在更新或者删除操作时,此注解必须加,否则会抛出下面异常

java.sql.SQLException: Can not issue data manipulation statements with executeQuery().

 遂添加注解,代码如下

1 public interface IStaffDao extends JpaRepository<Staff,Integer> {
2 
3     @Modifying
4     @Query(value="insert into role_persons(role_id,persons_id) values(?1,?2)",nativeQuery=true)
5     int insertRolePerson(long role_id,long persons_id);
6 }

执行后又抛出新的异常

javax.persistence.TransactionRequiredException: Executing an update/delete query
	at org.hibernate.internal.AbstractSharedSessionContract.checkTransactionNeededForUpdateOperation(AbstractSharedSessionContract.java:413)......

这里我查找资料后发现,似乎进行增删改操作的时候必须要有相关事务才可以,遂添加 @Transactional 注解,问题解决,代码如下:

1     @Transactional
2     @Modifying
3     @Query(value="insert into role_persons(role_id,persons_id) values(?1,?2)",nativeQuery=true)
4     int insertRolePerson(long role_id,long persons_id);

 

posted @ 2021-02-27 18:39  墨问苍生  阅读(395)  评论(0编辑  收藏  举报