我在将现有父实体与新子实体合并时遇到问题。
以下是该方案:
为什么会这样?难道不能为Child创建一个新条目吗?
父实体:
public class ParentEntity implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="PARENT_SEQ")
@SequenceGenerator(sequenceName="PARENT_SEQ",schema="MURTAZA YAHYA", name = "PARENT_SEQ", initialValue=-1)
//@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID",unique=true, nullable=false)
private Integer id;
@Column(name="NAME" , length=150)
private String name;
@OneToMany(mappedBy="parentEntity",cascade={CascadeType.MERGE,CascadeType.PERSIST})
List<ChildEntity> childEntities;
public Integer getId() {
if(id == null)
return null;
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ChildEntity> getChildEntities() {
return childEntities;
}
public void setChildEntities(List<ChildEntity> childEntities) {
this.childEntities = childEntities;
}
}
儿童实体
public class ChildEntity implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="CHILD_SEQ")
@SequenceGenerator(sequenceName="CHILD_SEQ",schema="MURTAZA YAHYA", name = "CHILD_SEQ" , initialValue=0)
//@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID",unique=true, nullable=false)
private Integer id;
@Column(name="NAME" , length=150)
private String name;
@ManyToOne
@JoinColumn(name="PARENT_ID")
private ParentEntity parentEntity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ParentEntity getParentEntity() {
return parentEntity;
}
public void setParentEntity(ParentEntity parentEntity) {
this.parentEntity = parentEntity;
}
}
public String AddChildToAnExistingParent(Parent p) {
// TODO Auto-generated method stub
ParentEntity parent = em.find(ParentEntity.class, p.getId());
ChildEntity childEntity = new ChildEntity();
childEntity.setName("INISYA");
childEntity.setParentEntity(parent);
List<ChildEntity> list = new ArrayList<ChildEntity>();
list.add(childEntity);
parent.setChildEntities(list);
em.merge(parent);
return "Success";
}
任何帮助将不胜感激。谢谢,
答案 0 :(得分:0)
由于 Parent-&gt; Child 关联使用CascadeType.PERSIST
注释,以下代码应解决所述方案。
public String AddChildToAnExistingParent(Parent p)
{ // TODO Auto-generated method stub
ParentEntity parent = em.find(ParentEntity.class, p.getId());
ChildEntity childEntity = new ChildEntity();
childEntity.setName("INISYA");
childEntity.setParentEntity(parent);
parent.getChildEntities().add (childEntity);
em.persist(parent);// the cascade.persist cause new childs persistence/insert
return "Success";
}
有关详细信息in this answer说明了EntityManager方法合并和 persist 的行为。