当Hibernate配置了(JPA注解)
cascade = { CascadeType.PERSIST, CascadeType.MERGE }
调用保存时
session.save(user);
并不能级联保存,因为save不会触发CascadeType.PERSIST。看save的javadoc:
/** * Persist the given transient instance, first assigning a generated identifier. (Or * using the current value of the identifier property if the <tt>assigned</tt> * generator is used.) This operation cascades to associated instances if the * association is mapped with {@code cascade="save-update"} * * @param object a transient instance of a persistent class * * @return the generated identifier */ Serializable save(Object object);
save会触发“save-update”和JPA的CascadeType.ALL,并不会触发CascadeType.PERSIST。JPA没有“save-update”的CascadeType,只能使用Hibernate的CascadeType,如果想保存时触发级联:
1. 可以使用JPA的CascadeType.ALL
2. 使用Hibernate的CascadeType.SAVE_UPDATE
@Cascade(CascadeType.SAVE_UPDATE)
触发其他JPA的CascadeType类型,请参见org.hibernate.session源码(或者javadoc)中各个方法,比如:
/** * Make a transient instance persistent. This operation cascades to associated * instances if the association is mapped with {@code cascade="persist"} * <p/> * The semantics of this method are defined by JSR-220. * * @param object a transient instance to be made persistent */ void persist(Object object);
也就是说该persist方法会触发JPA的CascadeType.PERSIST。
Hibernate支持的CascadeType类型,请见org.hibernate.annotations.CascadeType源码,或者javadoc