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 ind 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")
public class DetailEntity{
@Id
private Long id;
@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:
- Is it a bug or expected behavior?
- If this is expected behavior is there any way to achive desirable effect?