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);
  • 相关阅读:
    Sql ISNULL() 函数
    C#WinForm中按钮响应回车事件的简单方法
    职场升迁全攻略 人脉资源是铺垫
    怎样成为有钱人
    睡前应做六件事
    赚钱的秘诀(转)
    将Win2003转换成个人PC版系统
    抠图神器Inpaint 4.2
    iPhone升级记:从4.3.3到5.0.1:越狱篇
    iPhone升级记:从4.3.3到5.0.1:弯路篇
  • 原文地址:https://www.cnblogs.com/hellkey/p/14456796.html
Copyright © 2011-2022 走看看