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
非常感謝。 – 2013-03-25 18:55:51