使用JPA将连接表映射到Java中的Map对象

时间:2012-03-11 12:03:34

标签: mysql dictionary jpa join jointable

我有五个MySQL表

  • employee
  • qualification
  • institute qualification_institute(id,qualification_id, institute_id)
  • employee_qualification_institute(employee_id,qualification_institute_id)

qualification_institute定义了可获得的资格和机构之间的ManyToMany连接,而employee_qualification_institute告诉我们某个特定员工获得了他/她的资格。 EclipseLink在Set<QualificationInstitute>类中生成Employee字段,但我想要Map<Qualification, Institute>而不是Qualification。我该如何注释该地图?由于我有基于属性的访问权限,我是否需要在其getter方法中实现查询?

Set<Institute>类已包含Institute字段,而类Set<Qualification>包含Employee。如果我可以在EmployeeQualificationInstitute内注释地图,也许我可以避免必须有明确的{{1}}类。

1 个答案:

答案 0 :(得分:1)

在这种情况下你不能。由于按设计,每个研究所的资格并不是唯一的。我引用Map的JavaDoc:

  

将键映射到值的对象。地图不能包含重复的键;每个键最多可以映射一个值。

但是,EmployeeQualificationInstitute类不是必需的。

示例:

@Entity
public class Employee
{
    @Id
    @GeneratedValue
    private Long id;
    @JoinTable(name="EmployeeQualificationInstitute",
        joinColumns={
            @JoinColumn(name = "id", referencedColumnName = "employee_id")
        }
    )
    private Set<QualificationInstitute>
}

@Entity
public class Qualification
{
    @Id
    @GeneratedValue
    private Long id;
}

@Entity
public class Institute
{
    @Id
    @GeneratedValue
    private Long id;
}

@Entity
public class QualificationInstitute
{
    @EmbeddedId
    private QualificationInstitutePK key;

    @MapsId(value = "qualification_id")
    @ManyToOne
    @JoinColumn(name = "qualification_id", referencedColumnName = "id")
    private Qualification qualification;

    @MapsId(value = "institute_id")
    @ManyToOne
    @JoinColumn(name = "institute_id", referencedColumnName = "id")
    private Institute institute;
}

@Embeddable
public class QualificationInstitutePK
{
    @Column(name = "qualification_id")
    private Long qualification_id;

    @Column(name = "institute_id")
    private Long institute_id;
}