Hello,
I'm a little bit confused about a left join fetch behaviour.
In this test case, i try to fetch my 3 children using a left join fetch.
But my collection is null after closing the em.
It was expected to be fetched before closing the em, no ?
In fact, that is the objective of the fetch purpose (i guess ?).
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
public class ObjectDbTest {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(
"objectdb:$objectdb/db/test.tmp;drop");
EntityManager em = null ;
// Merge parent1
em = emf.createEntityManager();
if (! em.getTransaction().isActive()) {
em.getTransaction().begin();
}
MyEntity e1 = new MyEntity("parent1");
e1.addChild(String.valueOf("child1"));
e1.addChild(String.valueOf("child2"));
e1.addChild(String.valueOf("child3"));
em.merge(e1);
// Ok, seems to be well merged
em.getTransaction().commit();
em.clear();
em.close();
// Try to retrieve parent and children using left join fetch
em = emf.createEntityManager();
TypedQuery<MyEntity> query =
em.createQuery("SELECT DISTINCT m FROM MyEntity m JOIN FETCH m.entityChildren", MyEntity.class);
MyEntity myEntity = query.getSingleResult();
// Ok my em is now closed, let's check if children are retrieved
em.close();
emf.close();
if (myEntity.getEntityChildren() == null) {
System.out.println("Children not fetched !"); // We fall in this case, it is excepted ?
} else {
System.out.println("Number of children = " + myEntity.getEntityChildren().size());
}
}
@Entity
public static class MyEntity {
@Id
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Also tested with List
private Set <MyEntityChild> entityChildren = new HashSet <MyEntityChild> ();
MyEntity(String name) {
this.name = name;
}
public void addChild(String name) {
entityChildren.add(new MyEntityChild(name));
}
@ManyToMany(targetEntity = MyEntityChild.class, cascade = CascadeType.ALL)
public Set<MyEntityChild> getEntityChildren() {
return this.entityChildren;
}
public void setEntityChildren(Set <MyEntityChild> entityChildren) {
this.entityChildren = entityChildren ;
}
}
@Entity
public static class MyEntityChild {
@Id
private String name;
MyEntityChild(String name) {
this.name = name;
}
}
}
Regards,
Xirt