简体   繁体   English

JPA关系

[英]JPA Relationships

If you have a relationship like this : 如果您有这样的关系:

在此处输入图片说明

  • Employee many to one relationship to its supervising Employee 员工与其主管员工多对一关系
  • Employee many to one relationship to its department 员工与其部门多对一关系
  • Department one to one to its manager 部门经理一对一

I would write in the Employee entity: 我会在Employee实体中写:

@ManyToOne (cascade=CascadeType.PERSIST)
private Employee supervisor;
@ManyToOne (cascade=CascadeType.PERSIST)
private Department department;

and in the department 在部门里

@OneToOne (cascade=CascadeType.PERSIST)
private Employee manager;

I then would create and set the variables (name, title, salary, supervisor) of employee 然后,我将创建并设置员工的变量(名称,职务,薪水,主管)

Then I would create the department with his variables (name, code) 然后,我将使用他的变量(名称,代码)创建部门

With the departments created I then can set the department in the employees 创建部门后,我可以将部门设置为员工

And then I can set the manager in department. 然后我可以设置部门经理。

With all the variables set I can persist the entity's. 设置好所有变量后,我可以保留实体的变量。 I persist the Employees (because of the relationships the department will be persist also) 我坚持员工(因为部门之间的关系也会坚持)

I believe this is the right way to do this?! 我相信这是正确的方法吗?

While providing Annotation @ManyToOne; 在提供@ManyToOne注释时; also provide annotation @JoinColumn 还提供注释@JoinColumn

As right now u are only worried about persisting it will work fine. 现在,您只担心坚持下去会很好。 If later you want updates also to work in same way ; 如果以后您希望更新也以相同的方式工作; you would have to use CascadeType.ALL or CascadeType.MERGE 您将不得不使用CascadeType.ALL或CascadeType.MERGE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM