Search My Blog

Friday, April 10, 2015

@Where and @SQLDelete in Hibernate

Soft Delete
Many times, you want to delete an entity from your database, but you still want to keep a record of it. In such cases, we use soft deletes, ie, we mark the object as deleted using a flag in the record, but we do not remove it form the DB. This is called a soft delete.

Problem
Now, for each query you write, you need to append 'where isDeleted=false', to work with any active records.

Hibernate solution
In order to get rid of this boilerplate, Hibernate provides an annotation at the class level.

@Where(clause = "isDeleted != true")
class EntityName

Using this annotation, any select query on that entity gets appended with the where clause - 'where isDeleted != true'

(A more detailed explanation can be found here - http://java.dzone.com/articles/hibernate-where-clause)

And, in order to implement the soft delete, we can annotate the class with @SQLDelete.

@SQLDelete(sql = "update entityname SET isDeleted = true where objectkey = ?")

No comments:

Post a Comment