I've using JPA 2.0 with Hibernate 4.3.5 and trying to use Hibernate to auto generate my tables.
I've created the following entry in my Contact entity:
/**
* Address
*/
@Valid
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "contact_address", joinColumns = @JoinColumn(name = "contact_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "address_id", referencedColumnName = "id"))
@OrderColumn
private List<Address> addresses;
Hibernate is properly creating the contact table, but the join table is created without the correct PK:
CREATE TABLE `contact_address` (
`contact_id` bigint(20) NOT NULL,
`address_id` bigint(20) NOT NULL,
`addresses_order` int(11) NOT NULL,
PRIMARY KEY (`contact_id`),
UNIQUE KEY `UK_mvvtppjfu6d0lcjm83u5youn8` (`address_id`),
CONSTRAINT `FK_4fntyt0q2l6vkfg7t38pg4i94` FOREIGN KEY (`contact_id`) REFERENCES `contact` (`id`),
CONSTRAINT `FK_mvvtppjfu6d0lcjm83u5youn8` FOREIGN KEY (`address_id`) REFERENCES `address` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The PK listed here is only the contact_id
, which is incorrect. That will not allow me to have multiple addresses assigned. Rather, the PK should be a composite PK of contact_id
, address_id
.
Is Hibernate at fault, or is there something wrong in my JPA annotation? This is a one-way association.
As noted by a couple of people, technically speaking, I don't need a join table for a @OneToMany, but given that I need to use the Address entity in other entity objects, it is cleaner for me to use join tables for all the associations.
I have managed to hack around a solution using the @ManyToMany association and specifying a unique constraint on the join columns, but I am trying to understand if there is something wrong with my JPA or if it is a Hibernate bug.