mappedBy 單向關係不須要設置該屬性,雙向關係必須設置,避免雙方都創建外鍵字段數據庫中1對多的關係,關聯關係老是被多方維護的即外鍵建在多方,咱們在單方對象的@OneToMany(mappedby="")把關係的維護交給多方對象的屬性去維護關係。java
對於mappedBy複習下:
a) 只有OneToOne,OneToMany,ManyToMany上纔有mappedBy屬性,ManyToOne不存在該屬性;
b) mappedBy標籤必定是定義在the owned side(被擁有方的),他指向theowning side(擁有方);
c) 關係的擁有方負責關係的維護,在擁有方創建外鍵。因此用到@JoinColumn
d)mappedBy跟JoinColumn/JoinTable老是處於互斥的一方數據庫
這裏的維護關聯關係,拿多對多來講就是中間表,在不設置cascade的狀況下,中間表由負責維護關聯關係的一方維護app
舉例說明:ide
Game 和User 兩個實體類,他們是多對多的關係,有中間表t_game-user.對象
在User中配置有:blog
@ManyToMany(mappedBy="users") public List<Game> getGames() { return games; }
Game中配置有:get
@ManyToMany @JoinTable(name = "t_game_user", joinColumns = {@JoinColumn(name = "game_id",referencedColumnName="gameId")}, inverseJoinColumns = {@JoinColumn(name = "user_id",referencedColumnName="id")}) public List<User> getUsers() { return users; }
因此說由Game來維護他們的關聯關係,即中間表。表現形式:
1.由於沒有配置cascade因此分別給Game,User添加4條數據,而後手動在中間表中添加他們的關聯關係
2.在程序中執行刪除User
Hibernate: delete from t_user where id=?
Hibernate: delete from t_user where id=?
Hibernate: delete from t_user where id=?
Hibernate: delete from t_user where id=?
刪除了User,並無對中間表發生影響class
在程序中執行刪除Game
Hibernate:delete from t_game_user where game_id=?
Hibernate:delete from t_game_user where game_id=?
Hibernate:delete from t_game_user where game_id=?
Hibernate:delete from t_game_user where game_id=?
Hibernate:delete from t_game where game_id=?
Hibernate:delete from t_game where game_id=?
Hibernate:delete from t_game where game_id=?
Hibernate:delete from t_game where game_id=?
對中間表產生了影響,說明是Game在維護他們之間的關聯關係配置