Should referential integrity be handled manually through code when soft deleting records with "ACTIVE" column?

25 views Asked by At

I have a scenario in which instead of physically deleting a data from database, I am maintaining an "isActive" column for each entity. All the entities in consideration are managed by hibernate.

Lets consider following scenario in which entity Country has a to-one mapping inside Book. Presistable classes for both entities are as follows -

BookPersistable.java -

@Entity
@Table(
    name = "MY_BOOK"
)
@SQLDelete(
    sql = "update MY_BOOK set ACTIVE=false where ID=? AND VERSION=?"
)
@Where(
    clause = "ACTIVE = true"
)
public class BookPersistable {
  @Id
  @Column(
      name = "ID"
  )
  protected String id;

@Column(
      name = "ACTIVE",
      nullable = false
  )
  protected boolean active;

@OneToOne()
  protected CountryPersistable countries;

// getters and setters.
}

CountryPersistable -

@Entity
@Table(
    name = "COUNTRY"
)
@SQLDelete(
    sql = "update COUNTRY set ACTIVE=false where ID=? AND VERSION=?"
)
@Where(
    clause = "ACTIVE = true"
)
public class CountryPersistable {
  @Id
  @Column(
      name = "ID"
  )
  protected String id;

@Column(
      name = "ACTIVE",
      nullable = false
  )
  protected boolean active;

// getters and setters.

Here @SQLDelete annotation from hibernate is used to update the ACTIVE column to false when delete operation is triggered. Instead of physical delete it updates this column and makes the record inactive.

@Where annotation from hibernate is used to only fetch the active records.

My use-case is to stop the delete of a country which is refereed in any of the books. In case of physical delete the database takes care of it as we have Foreign keys enforced for referential integrity but in case of soft-delete do I need to manually establish this or is there any way out-of-the-box.

If we require manually handling of referential integrity, some recommendations on how to do it would be helpful.

Thanks.

0

There are 0 answers