Slava Gnedko
Slava Gnedko

Reputation: 13

How to use jpa or hibernate to prevent the deletion of the table

i have archive table that i don't want to be deleted so how to use jpa or hibernate to prevent the deletion of the table (delete method must throw an error), or when deleting actually do update (state = deleted). Is there any annotation or any technique to do so?

Upvotes: 1

Views: 1144

Answers (2)

sasau
sasau

Reputation: 26

You can use entity callback @PreRemove and throw runtime exception.

https://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html

Upvotes: 1

Devratna
Devratna

Reputation: 1008

The @SqlDelete annotation allows you to override the default DELETE statement executed by Hibernate, so we substitute an UPDATE statement instead. Therefore, removing an entity will end up updating the deleted column to true

@SQLDelete(sql = "UPDATE tag SET deleted = true WHERE id = ?")

@MappedSuperclass
public abstract class BaseEntity {

    private boolean deleted;
}

@Entity(name = "Tag")
@Table(name = "tag")
@SQLDelete(sql =
    "UPDATE tag " +
    "SET deleted = true " +
    "WHERE id = ?")
public class Tag extends BaseEntity {

    @Id
    private String id;

    //Getters and setters omitted for brevity
}

Upvotes: 0

Related Questions