0

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 KEY UK_3lunj2moakkbpehqwqkjcvlf4 (role_id), KEY FK_3lunj2moakkbpehqwqkjcvlf4 (role_id), KEY FK_ta3fwgh4sln85f6f3jjbte38u (board_id), KEY FK_lgd2b2mph9qoc1pe2h9r2wu8u (id), CONSTRAINT FK_lgd2b2mph9qoc1pe2h9r2wu8u FOREIGN KEY (id) REFERENCES users (id), CONSTRAINT FK_3lunj2moakkbpehqwqkjcvlf4 FOREIGN KEY (role_id) REFERENCES boardrole (role_id), CONSTRAINT FK_ta3fwgh4sln85f6f3jjbte38u FOREIGN KEY (board_id) REFERENCES boards (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.

1
  • 1
    I think adding @ManyToMany annotation to your map will remove the unique role_id constraint. Commented Nov 12, 2013 at 22:47

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, you're right. I removed @ElementCollection and I added @ManyToMany and the table look likes good. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.