JPA / JPQL: find root elements of a unidirectional tree.
I need some help to write a named query for the following problem.
I have the following (simplified) definition of an entity (TNode) and can save/read it via JPA.
The entity is unidirectional, so childs don’t know the parent!
Now I try to write a named query to get all root elements.
I use JPA 2.0 (Hibernate) and found some hints in the internet, that unidirectional links are supported.
A simple JUnit (4) is also attached, to create two trees and save it into the db. I removed all the asserts.
If I run the Junit, the table looks as expected:
ID NAME CHILDS_ID
1 A1 (null)
2 A11 1
3 B1 (null)
4 B11 3
I added @JoinColumn to have the self reference in the same table. And the with simple SQL the problem
would be easy (WHERE childs_id = null). But how must I write this in JPQL?
Thanks for the answers.
Uwe
@Entity
@Table(name = "TNode")
@NamedQueries({ @NamedQuery(name = "getRootNodes", query = "FROM TNode tnode ......."), })
public class TNode implements JPAObject {
@Id
@GeneratedValue
private Integer id;
private String name;
@OneToMany(cascade = { CascadeType.REFRESH, CascadeType.MERGE, CascadeType.REMOVE })
@JoinColumn
private Set<TNode> childs = new HashSet<TNode>();
// JPA only
private TNode() {
}
public TNode(String name) {
this.name = name;
}
public void add(TNode tNode) {
childs.add(tNode);
}
@Override
public Integer getId() {
return id;
}
@Override
public String getName() {
return name;
}
}
Here the simplified Junit
@RunWith(Arquillian.class)
public class TNodeTest {
@Deployment
public static Archive<?> createTestArchive() {
//@formatter:off
Archive<?> archive = ShrinkWrap.create(WebArchive.class, "test.war")
.addPackages(true, DummyInterfaceForTest.class.getPackage())
.addAsLibraries(FindMavenArtifact.find("com.thoughtworks.xstream:xstream:1.4.2"))
.addAsLibraries(FindMavenArtifact.find("xmlpull:xmlpull:1.1.3.1"))
.addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml")
.addAsResource("import.sql", "import.sql")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
//@formatter:on
System.out.println(archive.toString(true));
return archive;
}
@Inject
@DAO.DAOType(type = DAO.MODE.STATELESS)
private DAO<JPAObject> dao;
@Test
public void testMutipleRoots() throws Exception {
TNode root;
root = new TNode("A1");
root.add(new TNode("A11"));
dao.saveOrUpdate(root);
root = new TNode("B1");
root.add(new TNode("B11"));
dao.saveOrUpdate(root);
}
}
I found a solution by myself after reading a little bit about JPQL.
The (Sub-) Query solves the problem: