Orphan Removal on removing one child record, cascade="all-delete-orphan" exception

1k views Asked by At

//Sensitvity Table

public class Sensitivity implements Serializable {
    private static final long serialVersionUID = 1L;

    private long sensitivityId;

    public Set<SensitivityPattern> sensitivityPattern = new HashSet<SensitivityPattern>(0);

    public Sensitivity() {
    }

    @Id
    @SequenceGenerator(name=EntityConstants.SQ_SENSITIVITY_NAME, schema=EntityConstants.CDCIS_LAB_SCHEMA , sequenceName=EntityConstants.SQ_SENSITIVITY, allocationSize = 1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator=EntityConstants.SQ_SENSITIVITY_NAME)
    @Column(name="sensitivity_id", unique=true, nullable=false, precision=10, scale=0)
    public long getSensitivityId() {
        return this.sensitivityId;
    }

    public void setSensitivityId(long sensitivityId) {
        this.sensitivityId = sensitivityId;
    }

    @OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER,  mappedBy="sensitivity")
    public Set<SensitivityPattern> getSensitivityPattern() {
        return sensitivityPattern;
    }

    public void setSensitivityPattern(Set<SensitivityPattern> sensitivityPattern) {
        this.sensitivityPattern = sensitivityPattern;
    }

}

//SensitivityPattern

public class SensitivityPattern extends AuditableEntity implements Serializable {
 private static final long serialVersionUID = 1L;

 private long sensitivityPtId;

 private Sensitivity sensitivity;

 public SensitivityPattern() {}

 @ManyToOne(fetch = FetchType.EAGER)
 @JoinColumn(name = "sensitivity_id")
 public Sensitivity getSensitivity() {
  return sensitivity;
 }

 public void setSensitivity(Sensitivity sensitivity) {
  this.sensitivity = sensitivity;
 }

 @Id
 @SequenceGenerator(name = EntityConstants.SQ_SENSITIVITY_PATTERN_NAME, schema = EntityConstants.CDCIS_LAB_SCHEMA, sequenceName = EntityConstants.SQ_SENSITIVITY_PATTERN, allocationSize = 1)
 @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = EntityConstants.SQ_SENSITIVITY_PATTERN_NAME)
 @Column(name = "sensitivity_pt_id", unique = true, nullable = false, precision = 10, scale = 0)
 public long getSensitivityPtId() {
  return sensitivityPtId;
 }

 public void setSensitivityPtId(long sensitivityPtId) {
  this.sensitivityPtId = sensitivityPtId;
 }
//hash and equals overided.
}

//Code to delete Parent

 @Override
    public boolean saveSensitivityData(List < SensitivityDto > sensitivity, long orderId) throws LabWorkListException {
        if (sensitivity != null) {

            try {
                for (SensitivityDto dto: sensitivity) {
                    if (!dto.isIsSelected()) {
                        //senPatternRepo.deleteById(dto.getSensitivityId());
                        super.delete(dto);
                    }else {
                        dto.setInvstid(orderId);
                        updateSensitivityPattern(dto);
                        super.saveOneEntity(dto);
                    }
                }
            } catch (GenericException e) {
                logger.error("", e);

            }
        }
        return true;
    }

This is the code to delete one child.

 /**
     * To update the sensitivity data.
     * @param dto
     */
    private void updateSensitivityPattern(SensitivityDto dto) {
        if (dto != null && dto.getSensitivityPattern() != null) {
            for (SensitivityPatternDto sPattern: dto.getSensitivityPattern()) {
                sPattern.setSensitivity(dto);
                if (!sPattern.isIsSelected()) {
                      dto.setSensitivityPattern(null);
                    senPatternRepo.delete(sPattern.getSensitivityPtId());
                }
            }
        }
    }

Here on deleting one value in sensitivity table It throws exception

org.postgresql.util.PSQLException: ERROR: update or delete on table "lab_tb_sensitivity" violates foreign key constraint "fk_sensitivity_id" on table "lab_tb_sensitivity_pattern"

I had searched for a solution and find out orphanRemoval=true will solve this problem. Yes, its solved this problem.

But once orphanRemoval is added, when I delete a one child record its throws exception

 org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: om.gov.moh.model.cdc.Sensitivity.sensitivityPattern

How can I solve this problem.

or Q2) Can I delete the Parent, it should delete all the child automatically without using orphanRemoval = true ?

1

There are 1 answers

3
Tobb On BEST ANSWER

You are deleting an element that is still referenced in the parent.

With orphanRemoval removing a child element is as simple as:

parent.getChildren().remove(childToBeRemoved);

and then, if this is not done within a transaction:

em.merge(parent);