spring-jpa通过自定义sql执行修改碰到的问题
在编写自定义SQL的时候需要注意
@Query注解只能用来查询,想要进行添加、修改和删除操作需要配合@Modifying注解一同使用否则执行会报错错误信息如下,提示不支持修改操作1
2
3
("update AdminUser set username=:#{#adminUser.username},password=:#{#adminUser.password} where id=:#{#adminUser.id}")
int updateInfoById(@Param("adminUser") AdminUser adminUser);1
2
3
4org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [update com.leimo.module.adminuser.entity.AdminUser set username=:__$synthetic$__1,password=:__$synthetic$__2,updateTime=:__$synthetic$__3 where id=:__$synthetic$__4]; nested exception is java.lang.IllegalStateException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [update com.leimo.module.adminuser.entity.AdminUser set username=:__$synthetic$__1,password=:__$synthetic$__2,updateTime=:__$synthetic$__3 where id=:__$synthetic$__4]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:370) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]- 只是添加了
@Modifying注解在执行修改操作的时候仍然会报错,提示在进行删除和修改的时候需要给方法加上事务在可以直接在Repository的修改接口上添加1
2
3
4org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:402) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]@org.springframework.transaction.annotation.Transactional注解就可以正常执行修改语句了,或者在调用改接口的方法上添加@Transactional事务注解即可1
2
3
4
("update AdminUser set username=:#{#adminUser.username},password=:#{#adminUser.password} where id=:#{#adminUser.id}")
int updateInfoById(@Param("adminUser") AdminUser adminUser);
作者: 只是学习学习
邮箱: fengzxia1000@163.com
原文地址: https://fengzxia.gitee.io/posts/707abbe2.html
版权声明: 商业转载请联系作者获得授权,非商业转载请注明出处。