I'm using a pattern called "soft delete". Instesd of deleting entity I just mark it as deleted and prevent it from showing up in results of any query by adding @Where(clause = "rmv = false")
(rmv
is name of colum in database where I store the flag).
In one scenario this approach do not work.
Here is example:
@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;
}
When I try to get instance of MainEntity
from Hibernate with mainEntityRepository.findById(id)
I'm getting entity with detail != null
. Despite the fact that ther record in detail_entity
table have rmv = false
.
It produce following SQL query
select m.*, d.*
from main_entity m
left join detail_entity d
on m.id=d.main_id
where m.id=?
I expect it to have d.rmv=false
condition in where
clause.
My questions are:
EDIT Hibernate version: 6.1.7
This problem is solved in newer version of hibernate.
I checked and 6.5.2
works fine.