0
請在下面找到實體代碼,一個與同一實體很多關係
@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();
}
但在這種情況下,我在數據庫中有父對象,並希望堅持子對象什麼可能是可能的解決方案...?