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);
  • 相关阅读:
    PAT甲级——A1133 Splitting A Linked List【25】
    PAT甲级——A1132 Cut Integer
    PAT甲级——A1131 Subway Map【30】
    PAT甲级——A1130 Infix Expression【25】
    PAT甲级——A1129 Recommendation System【25】
    PAT甲级——A1128 N Queens Puzzle【20】
    PAT甲级——A1127 ZigZagging on a Tree【30】
    PAT甲级——A1126 Eulerian Path【30】
    PAT甲级——A1125 Chain the Ropes【25】
    集合的一个小发现
  • 原文地址:https://www.cnblogs.com/hellkey/p/14456796.html
Copyright © 2011-2022 走看看