【问题标题】:JPA - deleteBy query not working, orphanRemoval=true not workingJPA - deleteBy 查询不起作用,orphanRemoval=true 不起作用
【发布时间】:2021-11-19 10:25:18
【问题描述】:

我无法理解为什么JPA delete 不起作用。这是我的父实体:

public class RoleEntity {

 //...other attributes like name etc.

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
    @JoinColumn(name = "role_id", referencedColumnName = "id", nullable = false, insertable = false, updatable = false)
    private Set<RoleExtEntity> extensions;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "file_id", referencedColumnName = "id", nullable = false)
    private FileEntity fileEntity;
}

RoleRepository:

@Repository
public interface RoleRepository extends JpaRepository<RoleEntity, Long> {
   @Transactional
   int deleteByFileEntityAndName(FileEntity fileEntity, String roleName);
}

我正在尝试使用FileEntityRoleName 属性删除RoleEntitydelete 查询返回 val = 1 但是当我再次执行 findBy 时,它给了我记录而不是 null(因为我认为记录应该被删除,父子节点都应该被删除)。

FileEntity fileEntity = fileRepository.findByFolderId(id); 
RoleEntity roleToBeDeleted = roleRepository.findByFileEntityAndName(fileEntity, roleName);
int val = roleRepository.deleteByFileEntityAndName(fileEntity, roleName);
RoleEntity doesroleExistEntity = roleRepository.findByFileEntityAndName(fileEntity, roleName);

我已经尝试了这个平台上提到的各种解决方案,比如使用:

  • orphanRemoval = true
  • @Transactional注解
  • flush()
  • CascadeType.ALL

但是,它们似乎不起作用。有人可以让我知道我在这里做错了什么吗?谢谢!

更新:问题是我在代码中从持久性服务调用了错误的方法。该方法是 readOnlyTransaction(),它不允许我执行删除操作,因此我不得不使用另一种方法 withTransaction() 解决了我的问题。

【问题讨论】:

  • 它仍在一级缓存中,您正在获取缓存的实例。假设这是从本身是事务性的服务方法调用的,则在事务提交之前不会删除任何内容。此外,deleteByFileEntityAndName 实际上只会创建一个 delete 查询,它不* 使用元数据删除其余部分,只有在您自己执行 delete(RoleEntity) 时才会这样做。跨度>
  • @M.Deinum 我也试过RoleEntity roleToBeDeleted = roleRepository.findByFileEntityAndName(fileEntity, roleName); roleRepository.delete(roleToBeDeleted);,但它不起作用。我是JPA 的新手,所以如果您能详细说明如何提交交易会很有帮助?
  • 如果您在删除后立即再次查询,它仍然会存在于一级缓存中。如前所述,它只会在事务提交后被删除。假设您使用@Transactional,这将在服务方法执行后自动执行。您应该在 tx 提交后检查数据库,而不是在事务内部。
  • @M.Deinum 我已经在控制台上启用了记录 SQL 查询,但尽管调用了delete()deleteBy..(),我根本看不到删除查询。知道为什么会这样吗?

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


【解决方案1】:

当您调用我认为服务方法时会记录其他数据库查询? Yot 调用 jpa delete 方法。

JPA Method roleRepository.findByFileEntityAndName(fileEntity, roleName); 

return 一些东西可能会尝试显示检查。

【讨论】:

  • 实际上问题是我在代码中从持久性服务调用了错误的方法。该方法是readOnlyTransaction(),它不允许我进行删除,所以我不得不使用另一种方法withTransaction() 来解决我的问题。
猜你喜欢
  • 2015-09-29
  • 1970-01-01
  • 2014-01-19
  • 2016-12-26
  • 2017-02-25
  • 1970-01-01
  • 1970-01-01
  • 2018-03-20
  • 2019-07-16
相关资源
最近更新 更多