Hibernate:当嵌入式集合中的对象中维护多对一关系的多边时,如何设置按属性映射

时间:2012-05-31 09:02:39

标签: java hibernate jpa hibernate-mapping

我有2个实体和一个嵌入对象。为了保持讨论的通用性,我将称之为Project,ProjectAssociation(嵌入式对象),员工。

员工使用项目关联与Project关联。

我的业务要求是,我应该能够从员工中查找projectAssociation。此外,在未来我们可以期望projectAssociation获得更多属性。 projectAssociation的生命周期将始终与项目相关联。

项目和员工实体通过projectAssociation嵌入对象之间存在多对多的关系。

如何通过从项目到项目关联配置映射。?

Employee {
    Project projects;

    @OneToMany(mappedBy="What to set here?")
    public Set<Project> getProjects() {
        return projects;
    }

    public void setProjects(Set<Project> projects) {
        this.projects= projects;
    }
}

Project {
    Set<ProjectAssociation> projectAssocs;

    @Embedded
    @ElementCollection
    public Set<ProjectAssociation> getProjectAssociation() {
        return projectAssocs;
    }

    public void setProjectAssociation(Set<ProjectAssociation> hostRecovery) {
        this.projectAssocs = projectAssocs;
    }
}

ProjectAssociation {
// Parent association variable and methods are omitted for brevity
    Employee  employee;

    @ManyToOne
    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }
}

1 个答案:

答案 0 :(得分:0)

你需要将它作为@ManyToMany映射到中间表和外键列,然后设置Inverse(),以便Employee不会维护任何可链接的条目

@ManyToMany(...)
@Inverse()
public Set<Project> getProjects() {
    return projects;
}