Hibernate多对多映射,使用PK和额外列连接表

时间:2013-10-14 09:25:05

标签: java sql hibernate join

我对我的模型here进行了必要的更改。但是,我不知道在我的连接表实体上放什么。

请注意,我的联接表有一个代理键和两个额外的列(日期和varchar)。

到目前为止我得到的是:

User.java

@Entity
@Table (name = "tbl_bo_gui_user")
@DynamicInsert
@DynamicUpdate
public class User implements Serializable {
    private String id;
    private String ntName;
    private String email; 
    private Set<GroupUser> groupUsers = new HashSet<GroupUser>(0);

    // Constructors and some getters setters omitted

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.user", cascade=CascadeType.ALL)
    public Set<GroupUser> getGroupUsers() {
        return groupUsers;
    }

    public void setGroupUsers(Set<GroupUser> groupUsers) {
        this.groupUsers = groupUsers;
    }
}

Group.java

@Entity
@Table (name = "tbl_bo_gui_group")
@DynamicInsert
@DynamicUpdate
public class Group implements Serializable {
    private String id;
    private String groupName;
    private String groupDesc;
    private Set<GroupUser> groupUsers = new HashSet<GroupUser>(0);

    // Constructors and some getters setters omitted

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.group", cascade=CascadeType.ALL)
    public Set<GroupUser> getGroupUsers() {
        return groupUsers;
    }

    public void setGroupUsers(Set<GroupUser> groupUsers) {
        this.groupUsers = groupUsers;
    }
}

问题在于我不知道在连接表实体上放什么。在这里。

GroupUser.java

@Entity
@Table (name = "tbl_bo_gui_group_user")
@DynamicInsert
@DynamicUpdate
@AssociationOverrides({
    @AssociationOverride(name = "pk.user", 
            joinColumns = @JoinColumn(name = "id")),
    @AssociationOverride(name = "pk.group", 
            joinColumns = @JoinColumn(name = "id")) })
public class GroupUser implements Serializable {
    private String id;
    private User userId;
    private Group groupId;
    private Date dateCreated;
    private String createdBy;

    // constructors and getters and setters for each property

    // What now? ? No idea
}

1 个答案:

答案 0 :(得分:1)

用户到群组将是Many-To-Many关系。现在,您将其分为两个One-To-Many关系。因此,您的制图实体只需使用Many-To-Many

即可完成Many-To-One关系
public class GroupUser implements Serializable {
    private String id;

    @ManyToOne
    private User userId;

    @ManyToOne
    private Group groupId;
    private Date dateCreated;
    private String createdBy;
}

另见这个例子:Mapping many-to-many association table with extra column(s)(有38个赞成票的答案)