Spring 数据 JPA:不支持 DML 操作

Spring Data JPA: Not supported for DML operations

我已经为 Amazon Aurora 数据库编写了一个查询,用于删除一些对象,在我的界面中扩展 CrudRepository,但是当我执行查询时它抛出异常!

@Transactional
@Query("delete from HotelPrice hp where hp.updateDate < ?1 ")
void deletePriceOlderThan   (Date date);

异常跟踪:

Caused by: java.lang.IllegalStateException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [delete from com.gamesa.backend.persistence.domain.backend.HotelPrice hp where hp.updateDate < ?1 ]
    at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:554)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:208)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:87)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:499)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:477)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 35 common frames omitted

通过在查询方法上注解@Modifying.[=12=实现修改查询的执行实际上只需要参数绑定]

@Modifying 有效地删除 EntityManager 中所有未刷新的更改。如果您不希望 EntityManager 被自动清除,您可以将 @Modifying 注释的 clearAutomatically 属性设置为 false

工作代码将是:

@Transactional
@Modifying
@Query("delete from HotelPrice hp where hp.updateDate < ?1 ")
void deletePriceOlderThan   (Date date);

进一步阅读:

1. Spring Repostiories