Hibernate的cascade总结
1.JPA中的CascadeType.ALL并不等于{CascadeType.PESIST,CascadeType.REMOVE,CascadeType.MERGE,CascadeType.REFRESH}
在Hibernate中调用session.save() or session.update()并不能触发{CascadeType.PESIST,CascadeType.REMOVE,CascadeType.MERGE,CascadeType.REFRESH}的级联操作,而能触发CascadeType.ALL的级联。如不希望用CascadeType.ALL,需要使用Hibernate自身对cascade的注解@Cascade(value=org.hibernate.annotations.CascadeType.SAVE_UPDATE)
2.共享主键的OneToOne方式不能通过cascade来自动生成标识符,即使声明了@GenericGenerator(name="foreign_key",strategy="foreign",parameters={@Parameter(name="property",value="person")})
@Entity public class Person implements Serializable { @Id @GeneratedValue(generator = "g_id") public String getId() { return id; } @OneToOne(cascade = { CascadeType.PERSIST ,CascadeType.ALL}) @JoinColumn(name = "profile_id") @PrimaryKeyJoinColumn(name="id") public Profile getProfile() { return profile; } } @Entity public class Profile implements Serializable { @Id @GenericGenerator(name = "foreign_key", strategy = "foreign", parameters = { @Parameter(name = "property", value = "person") }) @GeneratedValue(generator = "foreign_key") public String getId() { return id; } @OneToOne(mappedBy = "profile") public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } }
3.delete-orphan只应用在OneToMany中,能级联删除Many集合中的子元素。
NOTE:JPA并不支持delete-orphan,但并不明白hibernate reference中为什么可以在OneToMany中添加属性orphanRemoval=true的属性。事实上,要用hibernate独有的注解@Cascade([email protected]_ORPHAN)来达到此目的