Cascade soft-delete with @MappedSuperclass in hibernate

1.3k Views Asked by At

I am working on a huge application with a complex database schema. I am using Spring and Hibernate for the development. I wanted to know how to soft-delete an entity(where the active field is there in a superclass rather than having in all the entities). I implemented the suggestion provided here.

Below is the structure of my entities and hibernate util classes

Base Entity

@MappedSuperclass   
public abstract class BaseEntity<TId extends Serializable> implements IEntity<TId> {

        @Basic
        @Column(name = "IsActive")
        protected boolean isActive;

        public Boolean getIsActive() {
            return isActive;
        }

        public void setIsActive(Boolean isActive) {
            isActive= isActive;
        }
    }

Child Entity :

@Entity(name="Role")
@Table(schema = "dbo")
public class Role extends BaseEntity {
    //remaining fields
    //1. foreign key reference to another entity
    //2. List<Child> entities 
    //3. Self reference fields

}

Hibernate Util Class:

public void remove(TEntity entity) {

    //Note: Enterprise data should be never removed.
    entity.setIsActive(false);
    sessionFactory.getCurrentSession().update(entity);
}

Now I have a few requirements with this which I am not able to solve now.

  1. When I delete 'Role' entity, all the children entities should also get deleted (soft delete only for all) :-> Do I need to fetch the parent entity, iterate through the children and delete one by one ?

  2. Role has a foreign-key reference with another entity 'Department'. If a department is deleted, the roles associated should get deleted conditionally(ie, only if the caller decides: in some cases, we dont want to delete the referred entities).

  3. There are some self-referencing column like 'ParentRoleId'. If a Role is deleted, all its referenced roles also should be deleted. -> Do I need to fetch the ID and then delete all the self-referenced children entities and then delete each? eg: Department can have a parent department(which is by using the field : parentdeptid). If I delete a parent department, all the sub-departments should get deleted

If anyone has any suggestions on how to do this, please let me know.

0

There are 0 best solutions below