Hibernate 总结关联关系

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

关键的属性设置

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:

  • 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.

你可能感兴趣的:(Hibernate 总结关联关系)