我正在开发一个应用程序,其中实体之间的关联如下。这里注释是所有者和迭代,用户是反向表。要求是 - 用户可以有类似的评论,多个用户可以给出评论。 迭代也可以有多个注释,单个注释可以属于多个迭代。
代码如下 -
评论实体 -
@Table(name="RCOMMENTS")
@Entity
public class RComment{
@Id
@Column(name="COMMENTID")
@GeneratedValue(strategy=GenerationType.AUTO)
private long commentid;
@Column(name="DESCRIPTION")
private String description;
@Column(name="TYPE")
private String type;
@ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@JoinTable(name = "COMMENTS_USERS", joinColumns = { @JoinColumn(name = "COMMENTID") },
inverseJoinColumns = { @JoinColumn(name = "USERID") })
private Set <RUsers> users = new HashSet<RUsers>();
@ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@JoinTable(name = "COMMENTS_ITERATIONS", joinColumns = { @JoinColumn(name = "COMMENTID") },
inverseJoinColumns = { @JoinColumn(name = "ITERATIONID") })
private Set <RIteration> iteration = new HashSet<RIteration>();
用户 -
@Entity
@Table(name = "RUSER")
public class RUsers {
@Id
@Column(name = "USERID")
@GeneratedValue(strategy=GenerationType.AUTO)
private long userid;
@Column(name = "USERNAME")
private String username;
@Column(name = "PASSWORD")
private String password;
@ManyToMany(mappedBy="users")
private Set <RComment> comment ;
迭代 -
@Table(name = "RITERATION")
@Entity
public class RIteration {
@Id
@Column(name = "iterationid")
@GeneratedValue(strategy=GenerationType.AUTO)
private long iterationid;
private Date startdate;
private Date enddate;
private long iter;
@ManyToMany(mappedBy="iteration")
private Set <RComment> comment = new HashSet<RComment>();
测试代码 -
RUsers user = (RUsers) session.get(RUsers.class, this.userid);
Set<RComment> comments = user.getComment();
现在面临的问题是映射表是空的。 user.getComment()也会产生空集
在我启动我的网络应用程序之前,我的数据库实体表预先填充了虚拟值。但是在运行期间我调试代码时user.getcomment返回空集。
有人可以帮我解决可能出现的问题。
答案 0 :(得分:0)
如果你的实体之间存在双向关系,那么当Hibernate将它们存储在数据库中时,它会注意只读取双方中的一方。
重要关系的一面是ManyToMany
注释不包含mappedBy
变量的那一方。这就是您需要分配值的一面:
RUsers user = ...
RComment comment = ...
comment.users.add(user); <--- that is the assignment hat hibernate will store!
user.comments.add(comment); <--- that assigment will NOT been stored by hibernate, but hibernate will load it from database