6

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.

uguurozkan
  • 321
  • 1
  • 3
  • 15

1 Answers1

1

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.

  • 3
    Keep in mind that this approach won't work properly for one-to-many relationships. For example, if you have an entity with `@OneToMany List children`, then `entity.getChildren().remove(0)` will trigger an actual `delete` query on persist. – Timekiller Jun 13 '19 at 15:48