JPA: persisting entity with composite primary key
I have two tables in database, A and B. Table B has an id composed of two
fields. One of them is a foreign key to A. Id of A is automatically
generated on insert by a sequence.
A:
ID (PK)
(*other fields*)
B:
SOME_FIELD (PK)
A_ID (PK, FK to A)
I have mapped the two tables in JPA (Hibernate) following JPA
specification, in this way:
@Entity
@Table(name = "A")
public class A {
@Id
@SequenceGenerator(name = "A_SEQ", sequenceName = "A_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "A_SEQ")
@Column(name = "ID")
private Long id;
(...)
}
@Entity
@Table(name = "B")
public class B {
@EmbeddedId
@AttributeOverride(name = "someField", column = @Column(name =
SOME_FIELD))
private BPK pk;
@MapsId("aId")
@ManyToOne
@JoinColumn(name = "A_ID")
private A a;
(...)
}
@Embeddable
public class BPK {
private Long aId;
private String someField;
@Override
public boolean equals(Object o) {
(...)
}
@Override
public boolean hashCode() {
(...)
}
(...)
}
The problem is that when I try to save an B object calling
entityManager.persist(b), where b.a is set to an A object, which exists
already in database, I get an exception:
javax.persistence.PersistenceException:
org.hibernate.PersistentObjectException: detached entity passed to
persist: package.name.A
I don't know why this happens. I'm trying to save object of class B, not
A. Is my entity class wrong? Or maybe I shouldn't use persist here?
No comments:
Post a Comment