我有多对一的关系,我试图坚持一个子实体.
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;
}
Run Code Online (Sandbox Code Playgroud)
Office Id已存在于数据库中.但员工不是.现在,如果我要添加一名员工,他的成绩必须进入办公室数据库.
当我执行以下操作时,成绩不会被保存
Office office = new Office();
office.setId(23);
office.setGrades(5);
employee.setOffice(office);
em.persist(employee);
Run Code Online (Sandbox Code Playgroud)
如何在一次操作中将成绩保存到办公台中
JB *_*zet 16
首先,修复您的映射.
该关联是双向的,并且必须使用mappedBy属性将其中一侧(一侧)标记为另一侧:
@OneToMany(mappedBy = "office")
public set<Employee> employees;
Run Code Online (Sandbox Code Playgroud)
员工只是办公室的员工之一.删除单个员工时,您真的想要删除整个办公室吗?如果没有,你为什么要cascade=cascadeType.ALL上一个@ManyToOne?那些注释会产生后果.不理解它们就不要使用它们.
现在要真正回答这个问题.如果办公室已存在于数据库中,则不应构建新的办公室.从数据库中获取并更新它:
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);
Run Code Online (Sandbox Code Playgroud)
现在您也可以将办公室附加到新员工.但由于它是双向关系,您还应该初始化关联的另一面以保持对象图形连贯:
employee.setOffice(office);
office.addEmployee(employee);
em.persist(employee);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24958 次 |
| 最近记录: |