2

I have a table Department with one to many mapping to Employee table and having cascade type as all.

@OneToMany(mappedBy="department",orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @Fetch(FetchMode.JOIN)
    private List<Employee> emp; 

In database , the child table(Employee) is having this constraint on foreign Key enter image description here


When Iam deleting a record from Department Table in Java Code , Using Hibernate *Delete Function with a Primary key as parameter,*it is Deleting the record from Department table as well as deleting all associated records to it in Employee Table. When Iam running below query (Dep_ref is not primaryKey)

delete from Department where Dep_ref= 99999;

So it should delete all records from Department Table, and associated records in Employee table. But,Iam getting below error.

SQL Error: ORA-02292: integrity constraint violated - child record found 02292. 00000 - "integrity constraint (%s.%s) violated - child record found" *Cause: attempted to delete a parent key value that had a foreign dependency. *Action: delete dependencies first then parent or disable constraint.

Can anyone Please Help me out to Fix this issue.

  • Try initializing your `emp` collection: `private List emp = new ArrayList<>();` and make sure it's fetched when you delete the `Department` (since it's lazy). – HBo May 09 '18 at 10:43

1 Answers1

0

The issue in your mapping. It is in the wrong direction. You should create the foreign key on Employee to reference Department.

// Departments
@OneToMany(mappedBy="departments", cascade=CascadeType.ALL)
@Cascade(org.hibernate.annotations.CascadeType.ALL)
private Set<Employee> emp;

// Employee
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="department_id" , referencedColumnName="id", insertable=false, updatable=false)
private Departments department;