一对多的关系

一对多映射通常只是多对一映射的双向关系。我们将采用与多对一映射相同的示例。

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    
}

这种关系在数据库中表示如下。 StackOverflow 文档

关于 jpa 一对多映射有两点需要记住:

  • 多对一方是关系的拥有方。该列定义在该侧。
  • 一对多映射是反面,因此必须在反面使用 mappedBy 元素。

完整的例子可以在这里提到