JPA:当 class 使用 EmbeddedId 时保持自我关系
JPA: persist self relationship when class uses EmbeddedId
我有这个自我关系
public class Estoria implements Serializable {
@EmbeddedId
protected EstoriaPK estoriaPK;
@ManyToOne
@JoinColumns({@JoinColumn(name = "id_estoria", referencedColumnName = "id", updatable = false, insertable = false, nullable = true)
,@JoinColumn(name = "id_projeto" , referencedColumnName = "id_projeto" , insertable = false, updatable = false)})
private Estoria subtask;
@OneToMany(mappedBy = "subtask",cascade = CascadeType.ALL)
private Collection<Estoria> subtasks;
}
和我的 ID
@Embeddable
public class EstoriaPK implements Serializable {
@Basic(optional = false)
@Column(name = "id", unique = true, nullable = false)
private int id;
@Basic(optional = false)
@NotNull
@Column(name = "id_projeto", unique = true, nullable = false)
private int idProjeto;
// GETTRs and SETTERs
}
而且我尝试坚持使用级联
public void persistSubtask(int idEstoria,Estoria subtask) {
try {
estoria = this.entityManager.createNamedQuery("Estoria.findById",Estoria.class)
.setParameter("id", idEstoria)
.getSingleResult();
subtask.setEstoriaPK(new EstoriaPK(0,estoria.getProjeto().getId()));
subtask.setSubtask(estoria);
this.entityManager.persist(subtask);
} catch (Exception e) {
throw new NoPersistException("falha ao persistir subtask");
}
}
这不起作用,因为我的外键没有持久化,是否有一些注释错误?
如果我尝试持久化一个集合因为它们的父引用不持久化而无法正常工作,是否还有其他注释问题需要我修复?
问题似乎是
insertable = false, updatable = false
我有这个自我关系
public class Estoria implements Serializable {
@EmbeddedId
protected EstoriaPK estoriaPK;
@ManyToOne
@JoinColumns({@JoinColumn(name = "id_estoria", referencedColumnName = "id", updatable = false, insertable = false, nullable = true)
,@JoinColumn(name = "id_projeto" , referencedColumnName = "id_projeto" , insertable = false, updatable = false)})
private Estoria subtask;
@OneToMany(mappedBy = "subtask",cascade = CascadeType.ALL)
private Collection<Estoria> subtasks;
}
和我的 ID
@Embeddable
public class EstoriaPK implements Serializable {
@Basic(optional = false)
@Column(name = "id", unique = true, nullable = false)
private int id;
@Basic(optional = false)
@NotNull
@Column(name = "id_projeto", unique = true, nullable = false)
private int idProjeto;
// GETTRs and SETTERs
}
而且我尝试坚持使用级联
public void persistSubtask(int idEstoria,Estoria subtask) {
try {
estoria = this.entityManager.createNamedQuery("Estoria.findById",Estoria.class)
.setParameter("id", idEstoria)
.getSingleResult();
subtask.setEstoriaPK(new EstoriaPK(0,estoria.getProjeto().getId()));
subtask.setSubtask(estoria);
this.entityManager.persist(subtask);
} catch (Exception e) {
throw new NoPersistException("falha ao persistir subtask");
}
}
这不起作用,因为我的外键没有持久化,是否有一些注释错误?
如果我尝试持久化一个集合因为它们的父引用不持久化而无法正常工作,是否还有其他注释问题需要我修复?
问题似乎是
insertable = false, updatable = false