Hibernate 中的“软删除”,具有 OneToOne 映射

问题描述 投票:0回答:1

我正在使用一种称为“软删除”的模式。除了删除实体之外,我只是将其标记为已删除,并通过添加

@Where(clause = "rmv = false")
rmv
是我存储标志的数据库中的列名称)来防止它显示在任何查询的结果中。

在一种情况下,这种方法不起作用。

这是示例:

@Entity
@Table(name = "main_entity")
public class MainEntity {

    @Id
    private Long id;

    @OneToOne(mappedBy = "main", cascade = CascadeType.ALL)
    private DetailEntity detail;
}
 
@Entity
@Table(name = "detail_entity")
@Where(clause = "rmv = false")
public class DetailEntity{
    @Id
    private Long id;

    @Column
    private Boolean rmv = false;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "main_id", nullable = false)
    private MainEntity main;
}

当我尝试使用

MainEntity
从 Hibernate 获取
mainEntityRepository.findById(id)
的实例时,我正在使用
detail != null
获取实体。尽管事实上
detail_entity
表中的记录有
rmv = false

它产生以下 SQL 查询

select m.*, d.* 
from main_entity m 
left join detail_entity d 
    on m.id=d.main_id 
where m.id=?

我希望它在

d.rmv=false
子句中具有
where
条件。

我的问题是:

  • 这是错误还是预期行为?
  • 如果这是预期的行为,有什么方法可以达到理想的效果?
java hibernate
1个回答
0
投票

还将 where 子句添加到父级 (MainEntity) OneToOne 映射。

@Entity
@Table(name = "main_entity")
public class MainEntity {

@Id
private Long id;

@OneToOne(mappedBy = "main", cascade = CascadeType.ALL)
@Where(clause = "rmv = false")
private DetailEntity detail;

}

© www.soinside.com 2019 - 2024. All rights reserved.