Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique constraint on join table

Tags:

hibernate

jpa

I have a user, who has a many books:

public class User {

    @OneToMany
    @Cascade( { org.hibernate.annotations.CascadeType.ALL })
    @JoinTable(name="user_book")
    private Set<Book> books;

}

this will create in database a join table:

|user_id|book_id|
-----------------
|1      |2      |
|1      |3      |
|2      |1      |  

Problem is that unique constraint is only on book_id column. That means 2 user can't have the same book. If I would like add to user(id:1) a book(id:1), then I got: BatchUpdateException: Duplicate entry

Is this normal ? or this is bug? If not a bug, how i can configure hibernate to create unique constraint on pair (user_id,book_id) not only on book_id in join table.

Hibernate: 3.6.4.Final

MySQL: 5.0.21

like image 516
chris Avatar asked Oct 07 '12 18:10

chris


1 Answers

Your association is a One To Many. This means that One user can have Many books. If you want to be able to have a book shared by several users, make it a ManyToMany association: a user would have several books, and a book would have several users.

like image 183
JB Nizet Avatar answered Sep 23 '22 17:09

JB Nizet