为 JPA 实体字段查找模型 table

Model Look up table for a JPA Entity Field

我正在尝试找出要使用的适当关系,以便为需要查找 table(UI 上的 Comboxbox 等价物)的 JPA 实体字段建模 select 值来自。下面是一个例子:

@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 注释应该是什么?

谢谢,

桑迪普约瑟夫

我认为您正在寻找从 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; 
}