@OneToMany与非主键Hibernate的关系

时间:2013-02-18 11:23:45

标签: hibernate java-ee entity-relationship one-to-many hibernate-onetomany

我有一个名为Team的 @Entity

    @Entity
    @Table(name="projects_participants")
    public class Team {

        @Id`enter code here`
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column
        private int id;



    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }


    @Column(name="participants_id")
    private int participants_id;

    public int getParticipants_id() {
        return participants_id;
    }

    public void setParticipants_id(int participants_id) {
        this.participants_id = participants_id;
    }









    /*
    @CollectionOfElements 
    private Set<Projects> projectsParticipant;

    @ManyToMany(fetch = FetchType.LAZY,mappedBy = "team")
    public Set<Projects> getProjectsParticipant() {
        return projectsParticipant;
    }


    public void setProjectsParticipant(Set<Projects> projectsParticipant) {
        this.projectsParticipant = projectsParticipant;
    }
        */
}

我有另一个bean名称项目,如

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "projects_participants", joinColumns = { 
        @JoinColumn(name = "project_id") }, 
        inverseJoinColumns = { @JoinColumn(name = "participants_id",referencedColumnName="participants_id")})
public Set<Team> getTeam() {
    return team;
}

public void setTeam(Set<Team> team) {
    this.team = team;
}

它工作正常,但问题是project_participants表有project_id和Team表的id。但我想要Team表的project_id和Participants_id。        project_participants表如下

enter image description here

参与者表格为* enter image description here

最后我想要的是表 project_participants 应该有 project_project_id participant_id (而不是team_id)。提前提交。

1 个答案:

答案 0 :(得分:0)

在我看来,你正试图模仿m:n关系,但没有使用正确的注释和原则。

1)将@ManyToMany@JoinTable结合使用,以模拟m {n关系,如jee5 api中所述。

2)不要像通过participants_id那样通过ID列建模与其他对象的关系。使用JPA,您可以使用对象而不是ID,因此您的列将是Participant

相关问题