请在下面找到实体代码,
@Entity
public class A implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY, mappedBy="parentActivity")
private Set<A> subActivities;
@ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
@JoinColumn(name = "PARENTACTIVITYID", insertable = true, updatable = true)
private A parentActivity;
// Getters, Setters, serialVersionUID, etc...
}
如果我们想要同时保持父母和孩子,那么下面的代码可以完美地运行
public static void main(String[] args) {
EntityManager em = ... // from EntityManagerFactory, injection, etc.
em.getTransaction().begin();
A parentActivuty = new A();
A subActivity1 = new A();
A subActivity2 = new A();
son.setParentActivity(parent);
daughter.setParentActivity(parent);
parent.setSubActivity(Arrays.asList(subActivity1, subActivity2));
em.persist(parent);
em.persist(son);
em.persist(daughter);
em.getTransaction().commit();
}
但是在这种情况下,我在数据库中有父对象,并希望持久保存子对象可能的解决方案......?
答案 0 :(得分:3)
您从数据库中获取父级,执行附件并保留两个孩子:
A parent = em.get(A.class, parentId);
A son = new A();
A daughter = new A();
son.setParentActivity(parent);
daughter.setParentActivity(parent);
em.persist(son);
em.persist(daughter);
parent.getSubActivities().add(son);
parent.getSubActivities().add(daughter);