Jpa-2.0 – JPA cascading persistence – many to one

I have a one - on - one relationship and I'm trying to stick to a sub - 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;
}

The office ID already exists in the database But employees are not Now, if I add an employee, his grades must enter the Office database

When I did the following operations, my grades were not saved

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

How to save grades to your desk in one operation

Solution

First, fix your mapping

The association is bidirectional, and one of the sides (one side) must be marked as the reciprocal of the other with the mappedby attribute:

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

The employee is just one of the employees in the office When deleting an individual employee, do you really want to delete the entire office? If not, why put a cascade = cascadetype on @ manytoone ALL? These comments have consequences Do not use them without understanding

Now really answer this question If the office already exists in the database, you should not create a new one Take it out of 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 can also attach the office to the new employee However, since it is a two-way relationship, you should also initialize the other side of the association to keep the object diagram consistent:

employee.setOffice(office);
office.addEmployee(employee);
em.persist(employee);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>