Reputation: 59
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 implements Serializable {
@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 implements Serializable {
@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 implements Serializable {
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?
Upvotes: 2
Views: 8527
Reputation: 930
It could be that the entity A is no longer being held by entity manager. Have you tried setting B.a with a "fresh" instance of A?
b.setA(get(b.a));
entityManager.persist(b);
The get(b.a)
method can be whatever you usually use to find entity A from your datasource e.g. entityManager.getReference(A.class, a.id);
Upvotes: 3