Over a million developers have joined DZone.

Hibernate: @Where Clause

· Database Zone

Sign up for the Couchbase Community Newsletter to stay ahead of the curve on the latest NoSQL news, events, and webinars. Brought to you in partnership with Coucbase.

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.

The Getting Started with NoSQL Guide will get you hands-on with NoSQL in minutes with no coding needed. Brought to you in partnership with Couchbase.

Topics:
java ,sql ,enterprise-integration ,hibernate ,persistence ,tips and tricks

Published at DZone with permission of Alexey Zvolinskiy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}