JPA 中实体之间的关系
一共有如下四种关系
- @ManyToOne
- @OneToMany
- @OneToOne
- @ManyToMany
ManyToOne (多对一)
Many-To-One relation between entities: Where one entity (column or set of columns) is/are referenced with another entity (column or set of columns) which contain unique values. In relational databases these relations are applicable by using foreign key/primary key between tables.
例:
From Employee to Department
多个员工属于同一个部门
OneToMany (一对多)
In a one-to-many relationship between Table A and Table B, each row in Table A is linked to 0, 1 or many rows in Table B.
例:
From Department to Employee
一个部门可以有多个员工
OneToOne (一对一)
In One-To-One relationship, one item can belong to only one other item. It means each row of one entity is referred to one and only one row of another entity.
例:
Department : Employee
一个部门对应一个员工
ManyTOMany (多对多)
Many-To-Many relationship is where one or more rows from one entity are associated with more than one row in other entity.
例:
Class : Teacher
在双向关系中,多个班级对应多个老师,多个老师对应多个班级。
此时会生成一张中间表 Teacher_Class
@JoinColumn
A Join Column in JPA is a column in the owner entity that refers to a key (usually a primary key) in the non-owner or inverse entity. The first thing that comes to mind after reading the above line is that JoinColumns are nothing but a Foreign Key Columns. Another thing to notice above is that we have used the terms owner and non-owner entities. For easy rememberability, the entity that has a join column is always the owning entity.
- ManyToOne mappings are always defined on the owning entity.