Just a hint, not sure if this solves it: why don't you use @ManyToMany
annotation and use @ElementCollection
instead? @ElementCollection
is usually associated with a @CollectionTable
and not with a @JoinTable
.
Hibernate - mapping three tables with annotations
-
30-07-2022 - |
Pregunta
I have three tables: User, Role, Board. Each user can have many boards, but in one board user can have only one role. I created three classes and I added annotations:
class User {
@Id
@GeneratedValue
@Column(name = "id")
private long id;
@Column(name = "mail")
private String mail;
...
@JoinTable(name = "userBoardRole",
joinColumns = @JoinColumn(name = "id", unique = false),
inverseJoinColumns = @JoinColumn(name = "role_id", unique = false))
@MapKeyJoinColumn(name = "board_id", unique = false)
@ElementCollection
private Map<Board, Role> boardRoleMap = new HashMap<Board, Role>();
}
class Role {
@Id
@GeneratedValue
@Column(name = "role_id")
private long id;
@Column(name = "name")
private String name;
...
}
class Board {
@Id
@GeneratedValue
@Column(name = "role_id")
private long id;
@Column(name = "name")
private String name;
...
}
Hibernate create a new table, which look like this:
CREATE TABLE
userboardrole
(id
bigint(20) NOT NULL,role_id
bigint(20) NOT NULL,board_id
bigint(20) NOT NULL, PRIMARY KEY (id
,board_id
), UNIQUE KEYUK_3lunj2moakkbpehqwqkjcvlf4
(role_id
), KEYFK_3lunj2moakkbpehqwqkjcvlf4
(role_id
), KEYFK_ta3fwgh4sln85f6f3jjbte38u
(board_id
), KEYFK_lgd2b2mph9qoc1pe2h9r2wu8u
(id
), CONSTRAINTFK_lgd2b2mph9qoc1pe2h9r2wu8u
FOREIGN KEY (id
) REFERENCESusers
(id
), CONSTRAINTFK_3lunj2moakkbpehqwqkjcvlf4
FOREIGN KEY (role_id
) REFERENCESboardrole
(role_id
), CONSTRAINTFK_ta3fwgh4sln85f6f3jjbte38u
FOREIGN KEY (board_id
) REFERENCESboards
(board_id
) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The problem is that the column role_id is unique. Is there any way, using annotations, to set column unique to false? Thank you for any help.
I'm using hibernate 4.2.2.
Solución