JPA实体字段的模型查找表

时间:2017-03-29 13:03:20

标签: jpa associations entity lookup relationships

我试图找出用于建模JPA实体字段的适当关系,该实体字段需要查找表(在UI上等效的Comboxbox)来从中选择值。以下示例:

@Entity
public class Employee {

    @Id
    private int employeeId;
    private String name;
    private Department department;
}
@Entity
public class Department  {

    @Id
    private int id;
    private String name;
}

部门的实例可以如下:

Id    | Name
-----------------------
100   | Human Resources
101   | Sales
102   | Finances

对于员工,部门字段应从上述之一获取值。两个实体中相应字段的JPA注释应该是什么?

谢谢,

Sandeep Joseph

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找从EmployeeDepartment的单向ManyToOne关系,如下所示:

@Entity
public class Employee {

    @Id
    private int employeeId;
    private String name;

    @ManyToOne
    @JoinColumn(name = "department_id", nullable = false)
    private Department department;
}

这意味着员工必须与单个部门相关联,部门可以与许多员工相关联。

如果您需要知道与某个部门相关联的员工列表,那么您可以通过添加以下内容来建立双向关系:

@Entity
public class Department  {

    @Id
    private int id;
    private String name;

    @OneToMany(mappedBy = "department")
    private Collection<Employee> employees; 
}