简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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