我已经对概述的模型进行了必要的更改 here 。但是,我不知道要在我的连接表实体上放置什么。
请注意,我的连接表有一个代理键和两个额外的列(日期和 varchar)。
到目前为止我得到的是:
用户.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
}
最佳答案
用户与组之间是一种多对多
关系。现在,您将其分成两个一对多
关系。因此,您的映射实体只需使用多对一
来完成多对多
关系:
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票赞成的答案)
关于java - Hibernate 多对多映射,使用 PK 和额外列连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19357116/