Hibernate: @Where clause

Recently I’ve worked on a part of project where are a lot of entities. As in many other projects with the same feature there was implemented “soft delete” approach. That’s mean that when someone deletes any entity it remains in a database but a special field (e.g. ‘isDeleted’) changes its value to true.
As you’ve already guessed in every SELECT operation for this kind of entities we need to apply condition:
WHERE isDeleted = false
It’s a little bit redundant and boring to append each time this condition to a SQL query. So I started look at solutions which could give me some elegant solution of the problem. Fortunately a colleague of mine have given me a hint how to deal with such cases. The answer is covered behind the Hibernate‘s annotation @Where.
Let’s consider how we can decorate an entity with the @Where annotation to avoid extra condition in regular SQL queries:
import org.hibernate.annotations.Where;
import javax.persistence.*;
@Entity
@Table
@Where(clause = "isDeleted='false'")
public class Customer {
@Id
@GeneratedValue
@Column
private Integer id;
@Column
private String name;
@Column
private Boolean isDeleted;
//Getters and setters
}
Now when you want to select Customer on JPA level you will always get only isDeleted=false records. It’s very convenient when you are working with “soft delete” or any other situation which requires permanent application of some condition. I hope it will be useful for your projects.