關聯關係分爲單向和雙向,一對多/多對一,多對多,是否使用鏈接表,取決於數據庫設計,具體寫法參考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.