【问题标题】:Why does JpaRepository.delete() retrieve an entity before it will delete it?为什么 JpaRepository.delete() 在删除实体之前检索它?
【发布时间】:2020-09-19 15:21:47
【问题描述】:

当我使用它的 id 删除一个实体时,我得到以下日志输出。

2020-09-19 17:07:35.536 DEBUG 14544 --- [nio-8080-exec-2] org.hibernate.SQL                        : select comment0_.id as id1_15_0_, comment0_.acceptedAsAnswer as accepted2_15_0_, comment0_.commentDate as commentD3_15_0_, comment0_.commenter_id as comment10_15_0_, comment0_.commenterIp as commente4_15_0_, comment0_.content as content5_15_0_, comment0_.dateDeleted as dateDele6_15_0_, comment0_.deleted as deleted7_15_0_, comment0_.deleter_id as deleter11_15_0_, comment0_.journal_entry_id as journal12_15_0_, comment0_.language_id as languag13_15_0_, comment0_.lastEditedOn as lastEdit8_15_0_, comment0_.likeTotal as likeTota9_15_0_, comment0_.owning_comment_id as owning_14_15_0_ from comments comment0_ where comment0_.id=?
2020-09-19 17:07:35.562 DEBUG 14544 --- [nio-8080-exec-2] org.hibernate.SQL                        : delete from comments where id=?

我正在构建一个使用 Amazon 数据库服务的 Web 应用程序,因此该应用程序发出的每个请求都需要额外付费。为什么spring会在删除之前先检索对象,有什么办法阻止它这样做?

【问题讨论】:

  • 请检查此链接。 stackoverflow.com/a/13240979/7976968。这个问题已经在那里回答了。进行选择的原因是休眠需要知道对象是否处于持久状态。
  • 谢谢大家,我现在明白了。

标签: spring spring-boot spring-data-jpa


【解决方案1】:

正如@Naim 指出的那样,hibernate 首先检索对象,因为可能存在拦截器。这是我使用 JpaRepository 实现存储库直接对数据库进行删除查询的解决方案。

@Modifying
@Transactional
@Query(nativeQuery = true, value = "DELETE FROM comments WHERE id = :id")
void deleteById(@Param("id") Long id); 

自定义方法deleteById 不需要先获取实体。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 2018-12-25
    • 2014-04-29
    • 2012-09-06
    • 2011-09-20
    • 1970-01-01
    • 2015-09-25
    相关资源
    最近更新 更多