我正在尝试在我的数据库(MySQL V5.1.61)中实现一个标记系统,然后让它在休眠状态下工作。以下是我的数据库的相关部分:
数据包含:
如果我这样做正确,那么“nir”应该有 3 个与他相关的标签,“食物”、“联谊会”和“暑期实习”。
我遇到的问题是在休眠中实现这种关系(使用注释):
UserHibernate 类(我正在使用 GWT,所以我需要单独的 hibernate 和 DTO 对象):
@Entity
@Table(name="user")
public class UserHibernate implements Serializable{
private int ID;
//removed fields for brevity
private Set<UserTagsHibernate> tags;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "uID")
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
/**
* @return the tags
*/
@OneToMany(mappedBy="user", fetch=FetchType.EAGER)
public Set<UserTagsHibernate> getTags() {
return tags;
}
/**
* @param tags the tags to set
*/
public void setTags(Set<UserTagsHibernate> tags) {
this.tags = tags;
}
}
UserTagsHibernate 类:
@Entity
@Table(name="usertags")
public class UserTagsHibernate {
private int usertagsID;
private UserHibernate user;
private TagsHibernate tags;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="userforeignkey")
public UserHibernate getUser() {
return user;
}
public void setUser(UserHibernate userHibernate) {
this.user = userHibernate;
}
@OneToOne
@JoinColumn(name="tagforeignkey")
public TagsHibernate getTags() {
return tags;
}
public void setTags(TagsHibernate tagsHibernate) {
this.tags = tagsHibernate;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "usertagsID")
public int getUsertagsID() {
return usertagsID;
}
public void setUsertagsID(int usertagsID) {
this.usertagsID = usertagsID;
}
}
TagsHibernate 类:
@Entity
@Table(name = "tags")
public class TagsHibernate {
private int tagID;
//removed for brevity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "tagID")
public int getTagID() {
return tagID;
}
public void setTagID(int tagID) {
this.tagID = tagID;
}
}
我遇到的问题是,当我尝试检索用户时,这里是“nir”,他出现了 3 次。我相信这是因为他有 3 个标签,所以出于某种原因,当我发出查询 "session.createCriteria(UserHibernate.class).add(Restrictions.eq("username", "nir")).list(); " 我得到一个长度为 3 的列表。任何想法为什么会发生这种情况?