0
votes

I have to delete the collection of child entity rows from Parent entity rows. But some how my parent entity also getting deleted.

I see above issue is due to "CascadeType.ALL" on @ManyToOne relationship side. But if i remove this CascadeType.ALL in @ManyToOne i am getting below exception when i perform persist on Parent which has child entity too.

org.springframework.dao.InvalidDataAccessApiUsageException: object references an unsaved transient instance - save the transient instance before flushing:

@Entity
public class Parent {
    @Id
    @Column(name = "ID")
    private Long id;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "parent", orphanRemoval=true)
    private Set<Child> childs = new HashSet<Child>();

 ...
}

@Entity
public class Child {
    @Id
    @Column(name = "ID")
    private Long id;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="PARENTID", nullable = false)
    private Parent parent;

  ...
}

Service class:

final Parent parent = parentDao.find(parentId, status);
parent.getChilds().clear();
1

1 Answers

0
votes

Added following methods in Parent class

public void addChild( Child child )
{
    children.add( child );
    child.setParent( this );
}

public void removeChild( Child child )
{
    children.remove( child );
    child.setParent( null );
}

And removed Child use removeChild on the Parent.