[英]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. 我在数据库A和B中有两个表。表B的ID由两个字段组成。 One of them is a foreign key to A. Id of A is automatically generated on insert by a sequence. 其中之一是A的外键。A的ID是在插入时由序列自动生成的。
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: 我已经按照JPA规范在JPA(休眠)中映射了两个表:
@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: 问题是,当我尝试保存一个调用entityManager.persist(b)的B对象(其中ba设置为数据库中已存在的A对象)时,出现异常:
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? 我正在尝试保存B类而不是A类的对象。我的实体类错了吗? Or maybe I shouldn't use persist here? 还是我不应该在这里使用persist?
It could be that the entity A is no longer being held by entity manager. 可能是实体A不再由实体管理者持有。 Have you tried setting Ba with a "fresh" instance of A? 您是否尝试将Ba设置为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);
get(ba)
方法可以是通常用于从数据源中查找实体A的任何方法,例如, entityManager.getReference(A.class, a.id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.