Hibernate-inverse

来源:互联网 发布:北大青鸟java 课程 编辑:程序博客网 时间:2024/05/24 20:06
inverse的使用注意:
1. 原理与目的:
    If enabled, Hibernate will not try to insert or update the properties defined by this join.
    nverse属性默认是false的表示由该方维护关联关系.
2. 使用
2.1 1对多
默认是flase
1对多的情况下,例如一个学校对应很多学生。一般学生也就是多的一方被设置为true,学校也就是单一的一方设置为False。这样,save(学校)时,学生也会被save。
如果2个都是设置为true,那么应该,save(学校),save(某学生),学校.getChildren().add(某学生)。最后一步是确保一致性。
顺序:先Save父(id为空),再Save子,然后在update所有。导致潜在问题:如果学校的id为not null,那么按照保存顺序,就可能出问题。

append:
关于one-to-many,上面提到的问题,hibernate3仍然没有解决, ,或者说本来就是逻辑上确实应该避免的问题.See the reference doc:
Very important note: If the foreign key column of a <one-to-many> association is declared NOT NULL, you must declare the <key> mapping not-null="true" or use a bidirectional association with the collection mapping marked inverse="true". See the discussion of bidirectional associations later in this chapter.

2.2 多对多
例如老师和学生,一个老师有很多学生,一个学生也有多个老师。如果双方都是Set,那么简单。
如果一方是List,一方是Set(List是顺序的,Set是无序非重的),那么List需要将inverse设置为false(index),Set设置为true(cannot set as index)

3. cascade和inverse
"cascade定义的是关系两端对象到对象的级联关系;而inverse定义的是关系和对象的级联关系。"