今天又深入了了解和测试了一下Hibernate cascade 和 inverse 。
Inverse
在Hibernate annotation 中inverse 默认值是"true" 当配置了mappedBy="…"时就相当于inverse="false"了。
Cascade
CascadeType类中有这样几个常量,ALL、PERSIST、MERGE、REFRESH、REMOVE 。
让代码说话吧:
@Entity
@Table(name = "Users")
public class User implements java.io.Serializable {
private String id;
private Rose rose;
public User() {
}
@Id
@Column(name = "Id", unique = true, nullable = false, insertable = true, updatable = true, length = 5)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY)
@JoinColumn(name = "Roseid", unique = false, nullable = false, insertable = true, updatable = true)
public Rose getRose() {
return this.rose;
}
public void setRose(Rose rose) {
this.rose = rose;
}
}
@Entity
@Table(name = "Rose")
public class Rose implements java.io.Serializable {
private String id;
private Set<User> users = new HashSet<User>(0);
public Rose() {
}
@Id
@Column(name = "Id", unique = true, nullable = false, insertable = true, updatable = true, length = 3)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
@OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER )
@JoinColumn(name="RoseId")
public Set<User> getUsers() {
return this.users;
}
public void setUsers(Set<User> userses) {
this.users = userses;
}
public void addUser(User user) {
user.setRose(this);
users.add(user);
}
当在user类中配置成cascade = { CascadeType.PERSIST, CascadeType.MERGE } 时,更新和删除两个级联时:
Hibernate: select user_.Id, user_.Enabledel as Enabledel1_, user_.Name as Name1_, user_.Password as Password1_, user_.Roseid as Roseid1_ from ERP.dbo.Users user_ where user_.Id=?
Hibernate: select rose_.Id, rose_.Enabledel as Enabledel0_, rose_.Name as Name0_, rose_.Parent as Parent0_ from ERP.dbo.Rose rose_ where rose_.Id=?
Hibernate: delete from ERP.dbo.Users where Id=?
可以正常删除!但是代码要这样写:
User user =new User("adm");
user.setRose(new Rose("adm")); //这句不加就不能删除,提示错误。除非数据库不加级联限制
userDao.delete(user);
当在user类中配置成cascade = { CascadeType.ALL } or cascade={} 时,无法删除。
更新时也类似于这种情况,注意rose类中的addUser(User user)方法。
再有fetch = FetchType.EAGER。在这里不是延时加载,如果设置成LAZY,在取得数据时怎么做好呢?看其他论坛的方法各有好处也有不好的地方,在找一个更方法。。。