标签:
一对一单向[oneToOne]
public class User {
private Group group;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="GROUP_ID")
public Group getGroup() { return group; }
public void setGroup(Group group) { this.group = group; }
}
public class User {
private Long groupID;
@Id
@Column(name = "GROUP_ID", length=1)
public Long getGroupID() { return groupID; }
public void setGroupID(Long groupID) { this.groupID = groupID; }
}
一对多[OneToMany]和多对一[ManyToOne]
public class Enterprise {
private Long enterpriseID;
@Id
@Column(name = "ENTERPRISE_ID", length = 8)
public Long getEnterpriseID() { return enterpriseID; }
public void setEnterpriseID(Long enterpriseID) { this.enterpriseID = enterpriseID; }
private Set<User> users = new HashSet<User>();
@OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, targetEntity = User.class, mappedBy = "enterprise")
public Set<User> getUsers() { return users; }
public void setUsers(Set<User> users) { this.users = users; }
}
public class User {
private Enterprise enterprise;
@ManyToOne(cascade = { CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH })
@JoinColumn(name = "ENTERPRISE_ID")
public Enterprise getEnterprise() { return enterprise; }
public void setEnterprise(Enterprise enterprise) { this.enterprise = enterprise; }
}
注意fetch = FetchType.EAGER,如果选择LAZY,hibernate在事物结束后会关闭session(好像是session的问题),那么无法在事物之外取到被join出来的记录,会提示session被关闭。
标签:
原文地址:http://www.cnblogs.com/ning2015/p/4739016.html