问题
I'm trying to make a composite primary key mapping and doesn't work.
The requisites are:
- The relation may be with
@IdClassannotation - I need the relationship with person entity be
@ManyToOne
My code:
@Entity
@IdClass(PhonePK.class)
public class Phone implements Serializable{
@Id
@Column(name = "codigo", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long code;
@Id
@ManyToOne
@JoinColumn(name = "person", referencedColumnName = "code", nullable = false)
private Person person;
@Basic
@Column(name = "number", nullable = false)
private Integer number;
//getters and setters
//equals and hashcode
}
public class PhonePK implements Serializable {
private Long code;
private Long person;
public PhonePK(){}
public PhonePK(Long code, Long person) {
this.code = code;
this.person = person;
}
//getters and setters
//equals and hashcode
}
public class Person implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "code", nullable = false)
private Long code;
//getters and setters
//equals and hashcode
}
They way I'm trying to persist:
//a lot of code
//em = Entitymanager
em.persist(person);
phone.setPerson(person);
em.persist(phone);
The error that I'm receiving is:
Caused by: javax.persistence.PersistenceException: org.hibernate.HibernateException: No part of a composite identifier may be null
回答1:
There is a high chance that the Person you are setting on the Phone entity doesn't have and ID yet. Persist doesn't garante and ID. It is recommended you also flush the transaction.
Related: ID not added on persis()
回答2:
I found an issue in hibernate.atlassian. I gave up the composite key and just put a foreign key from Person in Phone.
来源:https://stackoverflow.com/questions/35521486/no-part-of-a-composite-indentifier-may-be-null