使用JPQL进行更新数据时,update语句提示报错
报错提示如下:
ERROR 14148 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [update linuy.bean.branch.Branch_Info_Bean B set B.branch_code = :newBranch_code where B.branch_code = :oldBranch_code]; nested exception is java.lang.IllegalStateException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [update linuy.bean.branch.Branch_Info_Bean B set B.branch_code = :newBranch_code where B.branch_code = :oldBranch_code]] with root cause
org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [update linuy.bean.branch.Branch_Info_Bean B set B.branch_code = :newBranch_code where B.branch_code = :oldBranch_code]
给出的提示是,不支持该数据库操作语句的执行,我检查了jpql确定没有任何错误,但就是报错,我找了好久没发现问题,使用sql语句也不行。原本的jpql如下:
@Query(value = "update Branch_Info_Bean B set B.branch_code = :newBranch_code where B.branch_code = :oldBranch_code")
void updateBranch_Code(@Param("newBranch_code")String newBranch_code , @Param("oldBranch_code")String oldBranch_Code);
但是我注意到了一个点,@Query(),本身只是执行查询操作,我在里面使用update那不是会有问题吗?
顺着这一点去找,问题就就很好解决了。只需要在自己的jpql上添加上@Modifying注解即可,告诉ORM这里是执行的写入操作。
添加之后如下,问题顺利解决,此处记录一下。
@Modifying
@Query(value = "update Branch_Info_Bean B set B.branch_code = :newBranch_code where B.branch_code = :oldBranch_code")
void updateBranch_Code(@Param("newBranch_code")String newBranch_code , @Param("oldBranch_code")String oldBranch_Code);