简体   繁体   中英

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 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 ba 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?

It could be that the entity A is no longer being held by entity manager. Have you tried setting Ba with a "fresh" instance of A?

b.setA(get(b.a));
entityManager.persist(b);

The get(ba) method can be whatever you usually use to find entity A from your datasource eg entityManager.getReference(A.class, a.id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM