简体   繁体   中英

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:

@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; also provide annotation @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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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