Hibernate 总结关联关系

关联关系分为单向和双向,一对多/多对一,多对多,是否使用链接表,取决于数据库设计,具体写法参考reference。 java

关键的属性设置 sql

inverse true的一方不维护关联关系,不处理即外键字段的更新,若有关联表,维护关联表的插入和删除。若是两边都维护关系,会有多余无用的update语句。注意的地方,通常来讲,让子表方维护关系,在java代码中两边的关系都设置,代码(child.setParent,parent.getchildren.add),而设置了true的一方代码不会产生sql.若是有主表记录,并且没有cascade,只须要调save child,插入子表时外键也会插入,若是有用cascade,直接flush就能够了。若是主表数据也是新增,没有cascade,注意持久化语句调用的顺序,先调用主表,在调用子表,这样只会产生insert,若是有cascade,只须要save parent 数据库

cascade级联持久化操做,在代码中能够省去调用父子关系中子实体的持久化操做的代码,关键是孤儿单,当没有调用父实体的持久化操做,而仅仅改变关系(例如list.remove),remove掉的子实体会被自动delete 数据库设计

Here is what each cascade option means: ui

  • none - do not do any cascades, let the users handles them by themselves.
  • save-update - when the object is saved/updated, check the associations and save/update any object that require it (including save/update the associations in many-to-many scenario).
  • delete - when the object is deleted, delete all the objects in the association.
  • delete-orphan - when the object is deleted, delete all the objects in the association. In addition to that, when an object is removed from the association and not associated with another object (orphaned), also delete it.
  • all - when an object is save/update/delete, check the associations and save/update/delete all the objects found.
  • all-delete-orphan - when an object is save/update/delete, check the associations and save/update/delete all the objects found. In additional to that, when an object is removed from the association and not associated with another object (orphaned), also delete it.
相关文章
相关标签/搜索