Hibernate – apply @Where when fetching

I am using following annotation on my Hibernate entity class

@Table(name="cms_user", schema="public")
@Where(clause = "deleted = false")
public class User {

So it does not load records that are "soft deleted". But when I fetch this entity as part of another query:

queryRoot.fetch("cmsUser", JoinType.INNER);

this where clause is not applied and also deleted users are visible. Of course I can filter them out then, but I am looking for an efficient way to set this deleted = false on single place and @Where or some other hibernate class annotation is a great candiadate.

Is there any way how can I annotate my hibernate class so deleted = false is applied also for fetches and joins?

>Solution :

I didn’t test it but try to add @Where annotation to your joined entity instead, in other words to your @OneToMany annotation.

@Where(clause = "deleted = false")
@OneToMany(mappedBy = "joinedEntity", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<User> userList;

Leave a Reply