Ok, the minimal codes are here:
public final class Test {
public static void main(String[] args){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("$objectdb/db/test.odb");
EntityManager em = emf.createEntityManager();
EntityTransaction trans = em.getTransaction();
int iBlock = 3;
//* codes-1
for (int i = 1; i <= 3*iBlock; i++) {
trans.begin();
Node o = new Node();
Node p = em.find(Node.class, i/3);
if (null==p) System.out.printf("Node %d has no parent.%n", i);
o.setParent( p );
em.persist(o);
trans.commit();
}//*/
/* codes-2.
em.close();
em = emf.createEntityManager();
//*/
em.clear(); // codes-3
trans = em.getTransaction();
int iSum = 0;
for (int i=1;i<=3*iBlock;i++){
Node o = em.find(Node.class, i);
if (null== o){
System.out.printf("%s is not Node %n", o);
continue;
}
List<Node> sons = o.getSons();
if (null==sons){
System.out.printf("%s has no sons %n", sons);
continue;
}
int iCnt = sons.size();
System.out.printf("%d : type:Node, sons:%d %n",i, iCnt);
iSum += iCnt;
Iterator<Node> it = sons.iterator();
while (it.hasNext()){
Node en = it.next();
System.out.printf("child : %d %n", en.getId());
}
}
System.out.printf("The sum : %d %n", iSum);
em.close();
emf.close();
}
@Entity
static class Node {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@ManyToOne @JoinColumn(name="pid")
protected Node parent;
@OneToMany(mappedBy="parent",fetch=FetchType.EAGER)
protected List<Node> Sons;
public int getId() {
return id;
}
public Node getParent() {
return parent;
}
public List<Node> getSons() {
return Sons;
}
public void setParent(Node parent) {
this.parent = parent;
}
}
}
The ideal result is here:
Node 1 has no parent.
Node 2 has no parent.
1 : type:Node, sons:3
child : 3
child : 4
child : 5
2 : type:Node, sons:3
child : 6
child : 7
child : 8
3 : type:Node, sons:1
child : 9
4 : type:Node, sons:0
5 : type:Node, sons:0
6 : type:Node, sons:0
7 : type:Node, sons:0
8 : type:Node, sons:0
9 : type:Node, sons:0
The sum : 7
The bad result is here:
Node 1 has no parent.
Node 2 has no parent.
null has no sons
null has no sons
null has no sons
null has no sons
null has no sons
null has no sons
null has no sons
null has no sons
null has no sons
The sum : 0
I tried the "codes-2" or "codes-3", they work with "codes-1" to output the ideal result.
Only "codes-1" will output the bad result.
When the "codes-1" is comment in the second run, the ideal result appears.
So, is there any reasonable method than .clear()?