![](/img/trans.png)
[英]Why do I have to use @Modifying with @Transactional in spring data jpa?
[英]How do I issue a modifying query to remove a set of entities by their IDs with Spring Data JPA?
我試圖從我的數據庫中刪除大量的記錄。 每個記錄都有一個外鍵級聯,這樣,當通過JPA一次刪除一條記錄時,每次刪除需要大約5秒。
所以我決定寫一個像這樣的JPQL查詢:
@Repository
public interface MyTableRepository extends JpaRepository<MyTable, Long> {
@Query("delete from MyTable where id in :ids")
void deleteAllIds(@Param("ids") Long[] ids);
}
當我運行它或等效時, void deleteAllIds(@Param("ids") Set<Long> ids);
,我得到以下內容:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [delete from com.lh.clte.domain.content.business.Hotel where id in (:ids_0_, :ids_1_, :ids_2_, :ids_3_, ... for the entire array size)]
org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:293)
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:403)
org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:111)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy72.deleteAllId(Unknown Source)
我怎樣才能實現目標?
要執行修改查詢,您需要使用@Modifying
注釋該方法,如參考文檔中所述 。
請注意,發出刪除查詢不會導致調用受影響實體的任何生命周期回調,因為該語句是直接對數據庫執行的。 為了獲得名為issue的回調,給定標識符列表的findAll(…)
廣告將結果傳遞給deleteAll(…)
。
如果您不管理上述任何層中的事務,請確保您還使用@Transactional
以便在JPA要求的事務中運行查詢。
您可能想要編寫一個單獨的服務或類,您可以編寫一些原始sql。JPA允許您編寫本機sql,但是如果您打算用它去那么遠,您應該只編寫一些原始sql並處理它您自己,確保刪除FK適用的其他表中的記錄和任何相關記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.