2013-03-25 110 views
0

我目前正在开发桌面应用程序(J2SE)。我试图用jpa来坚持我的对象,但我有一些奇怪的结果。
我有一个可以有孩子的实体。当我坚持上面的对象时,它不会坚持自己的孩子。 这里是我的实体:
J2SE JPA持久性行为

@Entity 
@Table(name = "Group") 
public class Group { 

/** 
* The identifier 
*/ 
@Id 
@GeneratedValue(generator = "increment") 
@GenericGenerator(name = "increment", strategy = "increment") 
private int id; 
/** 
* The name label 
*/ 
@Column(name = "NAME", length = 60, nullable = true) 

private String name; 
/** 
* The parent 
*/ 

@ManyToOne 
@JoinColumn(name="PARENT_ID") 
private Group parent; 
/** 
* The children 
*/ 
@OneToMany(mappedBy="parent") 
private List<Group> children; 

/** 
* Default constructor 
*/ 
public Group() { 

} 

/** 
* Const using fields 
* 
* @param name 
* @param parent 
* @param children 
*/ 

public Group(String name, Group parent, 
     List<Group> children) { 
    super(); 
    this.name = name; 
    this.parent = parent; 
    this.children = children; 
} 

/** 
* @return the id 
*/ 
public int getId() { 
    return id; 
} 

/** 
* @param id 
*   the id to set 
*/ 

public void setId(int id) { 
    this.id = id; 
} 

/** 
* @return the name 
*/ 
public String getName() { 
    return name; 
} 

/** 
* @param name 
*   the name to set 
*/ 
public void setName(String name) { 
    this.name = name; 
} 

/** 
* @return the parent 
*/ 
public Group getParent() { 
    return parent; 
} 

/** 
* @param parent 
*   the parent to set 
*/ 

public void setParent(Group parent) { 
    this.parent = parent; 
} 

/** 
* @return the children 
*/ 
public List<Group> getChildren() { 
    return children; 
} 

/** 
* @param children 
*   the children to set 
*/ 
public void setChildren(List<Group> children) { 
    this.children = children; 
} 
} 

这里是我的测试方法:

... 

    // the entity manager 
    EntityManager entityManager = entityManagerFactory 
      .createEntityManager(); 
    entityManager.getTransaction().begin(); 

    // create a couple of groups... 
    Group gp = new Group("first", null, null); 
    Group p = new Group("second", null, null); 
    p.setParent(gp); 
    Group f = new Group("third", null, null); 
    f.setParent(p); 

    // set gp children 
    List<Group> l1 = new ArrayList<Group>(); 
    l1.add(p); 
    gp.setChildren(l1); 

    // set p children 
    List<Group> l2 = new ArrayList<Group>(); 
    l2.add(f); 
    p.setChildren(l2); 

    // persisting 
    entityManager.persist(gp); 

任何想法?
在此先感谢
Amrou

回答

1

您需要单独坚持所有实体,或在@OneToMany设置cascade=ALL

仅仅将该实体添加到集合将不会持续子实体。级联是使其他可到达的实体通过一个单一的entityManager.persist调用继续存在的魔法。

+0

非常感谢。 – 2013-03-25 18:55:51