It seems that I made a mistake somewhere but I can not see where.
JPA insists to generate a unique constraint on a FK of one-to-many
relationship on the child side. This constraint prevents me to insert more then one record in the child table.
Parent entity:
@Entity
@Table(name = "customer")
@Data
public class CustomerDto {
@Id
private Long id;
...
@Column(name = "notes")
private String notes;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id")
private List<EmailDto> emails = new ArrayList<>();
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id")
private List<PhoneDto> phones = new ArrayList<>();
}
Child 1:
@Entity
@Table(name = "email")
@Data
public class EmailDto {
@Id
private Long id;
@Column(name = "email", unique = true, length = 128)
private String email;
@ManyToOne(fetch = FetchType.LAZY)
private CustomerDto customer;
}
Child 2:
@Entity
@Table(name = "phone")
@Data
public class PhoneDto {
@Id
private Long id;
@Column(name = "phone_number", nullable = false, length = 32)
private String phoneNumber;
@OneToOne(fetch = FetchType.LAZY)
private CustomerDto customer;
}
Tables looks as I expect:
But this also generates an extra constraint for the foreign-key on the phone
side:
The email
table looks ok:
The unique-contrtaint that Hibernate generates on the phone
side ONLY allow me to insert ONE record per customer. If I trying to insert two phone numbers I get a duplicate key value violates unique constraint "phone_customer_id_key"
error.
If I change the JoinColumn definition on the CustomerDto.java
this way:
@JoinColumn(name = "customer_id")
—> @JoinColumn(name = "customer_idx")
then it works and and I can save 0..* phone numbers per a customer properly.
BUT, this modification generates a stupid table structure:
What I am missing here?
I can create a proper structure with simple SQLs and I can use customer_id
as a foreign keys in the child tables. But why JPA generates an extra unexpected constraint?