I have an abstract base class A
, which is a @MappedSuperClass
.
Also, there are several entity classes which extend from class A
. Class A
contains an attribute called STATUS
, which represents whether a record is deleted or not.
@MappedSuperclass
public abstract class A {
@Id
private Long id;
@Column(nullable = false)
private boolean status = true;
}
What I want is to be able to perform a soft delete on all the child classes from class A
with @SQLDelete
annotation. For example, I have a class B extends A
and whenever I call delete on class B
, I want it to update status of that record on database.
@Entity
@Table(name = "TempTable")
@SQLDelete(sql = "update TempTable set STATUS = 0 where ID = ?") //Basically, I don't want
//to write this in every
//class. Instead write
//it to class A once.
@Where(clause = "STATUS = 1")
public class B extends A {
private String alpha;
}
Right now I am able to soft delete, but in order to that I have to write @SQLDelete
annotation in every class. I don't want that repetition and want to write it in base class A
once. In there it will update status of that record.
Is this possible? If yes, how can I achieve it?
Thanks in advance.
To implement a soft delete, you need to override Hibernate's default remove operation. You can do that with an @SQLDelete annotation. This annotation allows you to define a custom, native SQL query that Hibernate will execute when you delete the entity.
And implementing soft delete is easy! You just add the “Is_Deleted” or “Delete_Date” column to your tables (or attributes to your Document) and replace all delete statement invocations in your application code to updates. And yes, you need to modify all retrieve statements to take into account this new attribute.
A common way to implement soft delete is to add a field that will indicate whether data has been deleted or not. This SQL command will permanently remove the product with id=1 from the table in the database.
If you must use @SQLDelete then I'm afraid there is no solution.
I've managed to implement a soft-delete mechanism with spring-data-jpa + hibernate and mapped super classes without using @SQLDelete, but it requires creating your own BaseRepository implementation to override the SimpleJpaRepositoryImpl, and then replacing the delete method with your softdelete implementation.
The way to do this is well described in the spring-data docs, here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With