hibernate 表关系的维护 主要通过如@oneToOne等标签标记。在这些关系中,重要的是mappedby的设置。
如:
@OneToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.REMOVE }, mappedBy="user", fetch = FetchType.LAZY)
@JoinColumn(name = "location_id", referencedColumnName = "id")
private UserLocation location;
@OneToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.REMOVE }, mappedBy="user", fetch = FetchType.LAZY)
@JoinColumn(name = "userinfo_id", referencedColumnName = "id")
private Userinfo userinfo;
@OneToMany(cascade = { CascadeType.PERSIST, CascadeType.REFRESH,
CascadeType.MERGE }, mappedBy = "user", fetch = FetchType.LAZY)
@OrderBy("id asc")
private List<Album> albums;
这三个属性,都设置了mappedBy,则说明他和这三个实体UserLocation, Userinfo, Album之间的关系由这三个实体中来维护,‘维护’的意思是说,这三个实体会出现与user的关联关系字段,既user_id(字段名称取决于mappedBy对应user在三个实体中对user_id起的具体名字)。 同时,user_id这个关系字段的增加、删除、修改均由三个实体发起,不能由User发起。
如:
public Userinfo getUserinfo() {
if (userinfo == null){
userinfo = new Userinfo();//CascadeType.PERSIST
userinfo.setUser(this);//mappedby user, set "user_id" in userinfo
}
return userinfo;
}
public List<Album> getAlbums() {
if (albums == null){
Album headAlbum = new Album();
headAlbum.setUser(this);
albums = new ArrayList<Album>();
albums.add(headAlbum);
}
return albums;
}
public UserLocation getLocation() {
if (location == null){
location = new UserLocation();
location.setUser(this);
}
return location;
}
在三个实体中分别定义User
UserLocation:
@OneToOne(cascade = { CascadeType.REFRESH, CascadeType.MERGE }, fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
UserInfo:
@OneToOne(cascade = { CascadeType.REFRESH, CascadeType.MERGE }, fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
Album:
@OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE }, fetch = FetchType.LAZY, mappedBy = "album", targetEntity = UserPhoto.class)
@OrderBy("rank asc")
private List<UserPhoto> photos;
然后对这些属性进行设置:
//transfer UserinfoDto to userinfo
if (userinfo != null){
userinfo.toObject(user.getUserinfo());
}
// create user photo wall Album
user.getAlbums();
if (location != null) {
location.toObject(user.getLocation());
}
如果去掉user中 userinfo中的定义 mappedBy="user",则各自维护自己的关系,那么
user表中会有userinfo_id值,userinfo中有user_id. 当设置了user.setUserinfo(new Userinfo()), 则会在user中设置userinfo_id, 设置了userinfo.setUser(user),则对应。
标签@JoinColumn(name = "userinfo_id", referencedColumnName = "id") ,userinfo_id为在user表中外键,对应userinfo表中的id主键。如果不需要在user中有userinfo的id,则删除该标签