How To Implement A Soft Delete With Hibernate: Update The Record Instead of Deleting It
How To Implement A Soft Delete With Hibernate: Update The Record Instead of Deleting It
@Entity
@SQLDelete(
sql = “UPDATE account SET state = ‘DELETED’
WHERE id = ?”,
check = ResultCheckStyle.COUNT)
public class Account { … }
www.thoughts-on-java.org
Implement a soft delete with Hibernate
Update state property in current session
Hibernate doesn’t parse the native query you provide to the
@SQLDelete annotation. It just sets the values of the bind parameters
and executes it. It, therefore, doesn’t know that you provided an SQL
UPDATE statement instead of a DELETE statement to the
@SQLDelete annotation. It also doesn’t know that the value of the
state property is outdated after it performed the delete operation.
If your code might use the entity object after it got deleted, you need
to update the state property yourself. The easiest way to do that is to
use a lifecycle callback, as I do in the following code snippet. The
@PreRemove annotation on the deleteUser method tells Hibernate to
call this method before it performs the remove operation. I use it to
set the value of the state property to DELETED.
@Entity
@SQLDelete(
sql = “UPDATE account SET state = ‘DELETED’
WHERE id = ?”,
check = ResultCheckStyle.COUNT)
public class Account {
@PreRemove
public void deleteUser() {
this.state = AccountState.DELETED;
}
www.thoughts-on-java.org
Implement a soft delete with Hibernate
Exclude “deleted” entities in queries
Hibernate’s @Where annotation allows you to define an SQL snippet
which Hibernate adds to the WHERE clause of all queries. The
following code snippet shows a @Where annotation that excludes a
record if its state is DELETED.
@Entity
@SQLDelete(
sql = “UPDATE account SET state = ‘DELETED’
WHERE id = ?”,
check = ResultCheckStyle.COUNT)
@Where(clause = “state <> ‘DELETED'”)
public class Account { … }
As you can see in the following code snippets, Hibernate adds the
defined WHERE clause when you perform a JPQL query or call the
EntityManager.find method.
www.thoughts-on-java.org