3

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.

Community
  • 1
  • 1
Yadu Krishnan
  • 3,492
  • 5
  • 41
  • 80
  • Its all going to depend on how you set up your cascades, and orphan removal. I wish I could be more specific, but with such a complex example, it would take too much time to work out all your dependencies – JamesENL Jun 05 '14 at 06:59
  • Can you please tell me how to do it for a simple scenario in my case? – Yadu Krishnan Jun 05 '14 at 09:05
  • have you found solution? I have same task, with jpa and Spring Data. – demon101 May 22 '15 at 07:11
  • @demon101 Nope. Deleting the children tables responsibility is given to each of the parents. Before the parent delete is performed, I am explicitly calling the children delete methods. – Yadu Krishnan May 22 '15 at 07:48

0 Answers0