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.*;

@Where(clause = "isDeleted='false'")
public class Customer {

    private Integer id;

    private String name;

    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.

About The Author

Mathematician, programmer, wrestler, last action hero… Java / Scala architect, trainer, entrepreneur, author of this blog

  • Ben Cheng

    Hi Alex, thank you so much for putting this tutorial together. Does the @Where work with OneToMany relationships and collections/sets?

    • Ben, I’m not sure
      Because I worked last time with Hibernate more than 3 years ago
      So you’d better to look at its official docs

  • Tejprakash Singh

    How can i change Where clause for a particular query. i.e. i want to retrieve a soft deleted row without changing @Where(clause = “isDeleted=’false'”) in Customer Entity.