一對多的關係
一對多對映通常只是多對一對映的雙向關係。我們將採用與多對一對映相同的示例。
Employee.java
@Entity
public class Employee {
@TableGenerator(name = "employee_gen", table = "id_gen", pkColumnName = "gen_name", valueColumnName = "gen_val", allocationSize = 100)
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "employee_gen")
private int idemployee;
private String firstname;
private String lastname;
private String email;
@ManyToOne
@JoinColumn(name = "iddepartment")
private Department department;
// getters and setters
}
Department.java
@Entity
public class Department {
@TableGenerator(table = "id_gen", pkColumnName = "gen_name", valueColumnName = "gen_val", name = "department_gen", allocationSize = 1)
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "department_gen")
private int iddepartment;
private String name;
@OneToMany(mappedBy = "department")
private List<Employee> employees;
// getters and setters
}
這種關係在資料庫中表示如下。
關於 jpa 一對多對映有兩點需要記住:
- 多對一方是關係的擁有方。該列定義在該側。
- 一對多對映是反面,因此必須在反面使用 mappedBy 元素。
完整的例子可以在這裡提到