Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA cascade persist - many to one

Tags:

jpa-2.0

I have a many to one relationship and I am trying to persist a child entity.

public class Office
{
public int id;
public int grades;
@OneToMany
public set<Employee> employees;
}

public class Employee{
@GeneratedValue(strategy=GeneratedValue.identity)
public int empid;
@ManyToOne(cascade=cascadeType.ALL)
public Office office;
}

Office Id is already present in the database. But employee is not. Now if i am adding an employee and his grades must go into the office database.

When i do the following operation,grades are not getting saved

Office office = new Office();
office.setId(23);
office.setGrades(5);
employee.setOffice(office);
em.persist(employee);

How to save grades into the office table in a single operation

like image 467
Vignesh Avatar asked Aug 13 '11 07:08

Vignesh


1 Answers

First, fix your mapping.

The association is bidirectional, and one of the side (the one side) must be marked as the inverse of the other using the mappedBy attribute:

@OneToMany(mappedBy = "office")
public set<Employee> employees;

The employee is only one of the employees of the office. Do you really want to delete the entire office when you delete a single employee? If not, why do you put a cascade=cascadeType.ALL on the @ManyToOne? Those annotations have consequences. Don't use them without understanding them.

Now to really answer the question. If the office already exists in the database, you should not build a new one. Go fetch it from the database and update it:

Office office = em.find(Office.class, 23);
// office is now attached, and any change you make on the entity will be written to the database
office.setGrade(5);

Now you may also attach the office to the new employee. But since it's a bidirectional relationship, you should also initialize the other side of the association to keep the object graph coherent:

employee.setOffice(office);
office.addEmployee(employee);
em.persist(employee);
like image 94
JB Nizet Avatar answered Oct 21 '22 13:10

JB Nizet