PHP群:95885625 Hbuilder+MUI群:81989597 站长QQ:634381967
    您现在的位置: 首页 > 开发编程 > Java教程 > 正文

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

    作者:admin来源:网络浏览:时间:2021-02-27 20:17:34我要评论
    导读:在做一个接口的时候,数据库插入出现错误关键代码如下:publicinterfaceIStaffDaoextendsJpaRepository<Staff,Integer>{@Query(value="inse...
    在做一个接口的时候,数据库插入出现错误

    关键代码如下:

    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操作,在更新或者删除操作时,此注解必须加,否则会抛出下面异常

    1. 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); 

    执行后又抛出新的异常
     

    1. javax.persistence.TransactionRequiredException: Executing an update/delete query 
    2.     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); 


     

    转载请注明(B5教程网)原文链接:https://b5.mxunkeji.com/content-156-6515-1.html
    相关热词搜索:
    下一篇:最后一页