create table user_ ( user_id number(8,0) not null, user_password VARCHAR2(50), user_name VARCHAR2(50), constraint PK_USERS primary key (user_id) ); create table role_ ( role_id number(8,0) not null, role_name VARCHAR2(20), constraint PK_ROLES primary key (role_id) ); create table user_role ( role_id number(8,0) not null, user_id number(8,0) not null, constraint PK_USER_RELATE_ROLE primary key (role_id, user_id), constraint fk_1 FOREIGN KEY(role_id) REFERENCES role_(role_id), constraint fk_2 FOREIGN KEY(user_id) REFERENCES user_(user_id) );
上面的代碼,在oracle中創建了表的多對多關系,主要套路就是中間表這里,我們將role_id和user_id設置為聯合主鍵,然后分別設為用戶表和角色表的外鍵。



這里JPA就自動判斷出是多對多關系,最終我們在實體類中就生成兩個表而不是三個表
判斷主控方,我們看mapperBy屬性的值就可以了,這里就是role表是主控方,這個屬性定義了哪個類是雙向關系的維護端。

中間表在實體類中以注解的方式進行體現。

PS:我在別人的博客上有看到另一種多對多的寫法,給中間表一個ID作為主鍵,然后將role_id和user_id分別設為用戶表和角色表的外鍵,但這種寫法我沒試過。

