Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Hibernate: @Where Clause

DZone's Guide to

Hibernate: @Where Clause

· Database Zone
Free Resource

Learn how to move from MongoDB to Couchbase Server for consistent high performance in distributed environments at any scale.

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.

Want to deliver a whole new level of customer experience? Learn how to make your move from MongoDB to Couchbase Server.

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 DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}