zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    007_2 (变式)青蛙跳台阶
    008 二进制中1的个数
    009 数值的整数次方
    007_1 斐波那契数列的非递归解法
    Linux TTY函数跟踪
    Linux UART介绍
    Linux TTY介绍
    Linux音频编程
    Jasper语音助理
    Raspberry Pi使用
  • 原文地址:https://www.cnblogs.com/hellkey/p/14456796.html
Copyright © 2011-2022 走看看