我目前正在开发一个桌面应用程序(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);
任何想法?
提前
感谢阿姆鲁