I'm running into an issue where Hibernate is adding an (apparently) incorrect unique constraint on a database table when I use a composite primary key. My setup is below:
Hibernate version: 3.6.10
Tables (the names have been changed to protect the innocent):
- USER - represents a user.
- BOOKS - represents a book.
- USER_BOOKS - tracks the relationship between users and books.
For various reasons, I do not want the user object to have the mappings for books, and vice-versa, so I am opting to create the USER_BOOKS entry myself.
Since the USER_BOOKS table is a join table, I want to use a composite primary key consisting of the USER_ID and the BOOK_ID, and not have a separate ID just for this table. Using the Hibernate docs on composite primary keys (http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html_single/#d0e4819), I settled on using multiple @ID annotations in my UserBook object to specify my composite key. So my mapping looks like the following:
Code:
@Entity
public class UserBooks extends AuditedEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@OneToOne
@JoinColumns({
@JoinColumn(name="BOOK_ID", referencedColumnName="ID", unique=false)
})
private Book book;
@Id private Long userId;
@Enumerated(EnumType.STRING)
@Column(nullable=false)
private UserBookRelType relType;
... getters and setters ...
}
@Entity
@XmlRootElement
public class Book extends AuditedEntity {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String id;
... other properties and getters and setters ...
}
Everything looks good in the generated USER_BOOKS table (primary keys is set correctly and the join is correct),
except for the addition of a unique constraint being placed on the BOOK_ID. This unique constraint prevents more than 1 user from having a relationship to a BOOK, which is incorrect. I've tried various mechanisms to prevent hibernate from generating that constraint, but so far have had no luck :(
Can anyone shed some light on:
1). Why is the unique constraint being created in the first place?
2). How can I prevent it from being created?
Thanks in advance!