gpt4 book ai didi

Spring 数据 JPA : deleteById does not delete record from database but derived delete method does

转载 作者:行者123 更新时间:2023-12-05 03:42:05 27 4
gpt4 key购买 nike

我在我的 Spring 应用程序中观察到一种奇怪的行为。不幸的是我不能分享完整的代码,但基本上是这样的:

// the repository
@Repository
public interface InboxRepo extends JpaRepository<Inbox, Long> {}

// the service
@Transactional
public void deleteInbox(long id) {
inboxRepo.deleteById(id);
}

当调用 deleteInbox() 时,没有异常或任何类型的错误,但 Inbox 项目没有从数据库中删除。设置 spring.jpa.show-sql=true 表明甚至没有 DELETE 语句,即无论出于何种原因,代码实际上并没有发出删除。

在存储库中定义派生的删除方法时,删除有效,但对我来说还没有意义:

@Repository
public interface InboxRepo extends JpaRepository<Inbox, Long> {

// this seems to work
@Modifying
@Query("delete from Inbox i where i.id = ?1")
void delete(long id);
}

直接通过 EntityManager 删除也可以。但是,“标准”JpaRepository 方法在这里不起作用的原因可能是什么?

最佳答案

我找到了根本原因。有另一个实体引用了 Inbox,如下所示:

@OneToMany(mappedBy = "inbox", cascade = ALL, fetch = FetchType.EAGER)
private Set<Inbox> inbox = new HashSet<>();

FetchType.EAGER 与级联结合导致了问题,即一旦删除了 Inbox,此引用就导致了 Inbox 得到“重新坚持”。设置 FetchType.LAZY 解决了问题。

关于 Spring 数据 JPA : deleteById does not delete record from database but derived delete method does,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67419259/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com