J2SE JPA持久化行为

时间:2013-03-25 01:00:40

标签: java hibernate jpa persistence

我目前正在开发桌面应用程序(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 个答案:

答案 0 :(得分:1)

您需要单独保留所有实体,或在cascade=ALL上设置@OneToMany

仅将实体添加到集合中将不会持久保存子实体。 Cascade是通过单次entityManager.persist调用使其他可达实体持续存在的神奇之处。