简体   繁体   English

与同一实体的一对多关系

[英]One to Many Relationship with same Entity

Please find below entity code, 请在下面找到实体代码,

@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...
}   

if we want to persist parent and child both at the same time then below code works perfectly fine 如果我们想同时坚持父母和孩子,那么下面的代码可以完美地运行

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();
}

but here in this case i have parent object in the database and want to persist child object what could be the possible solution...? 但在这种情况下,我在数据库中有父对象,并希望持久保存子对象可能的解决方案......?

You get the parent from the database, do the attachments, and persist the two children: 您从数据库中获取父级,执行附件并保留两个子级:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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