JPA级联仍然存在-多对一 [英] JPA cascade persist - many to one
问题描述
我有一对多的关系,并且我试图保留一个子实体.
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已存在于数据库中.但是员工不是. 现在,如果我要添加一名员工,并且他的成绩必须进入办公室数据库.
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
推荐答案
首先,修复您的映射.
First, fix your mapping.
关联是双向的,并且必须使用mappingBy属性将一侧(另一侧)标记为另一侧的反向:
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;
员工只是办公室的员工之一.删除单个员工时,您真的要删除整个办公室吗?如果不是,为什么将cascade=cascadeType.ALL
放在@ManyToOne
上?这些注释会产生后果.不要在不了解它们的情况下使用它们.
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);
这篇关于JPA级联仍然存在-多对一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!