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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With