Pregunta

I've got Nodes that have a List<Node> of children Nodes. Following JPA conventions I end up with the following tables:

t_nodehas the attributes id, name, and department

t_node_t_node has the attributes t_node_id and childNodes_id

I want to return a list of a parent node's children nodes. How do I write the entitymanager query to do so?

The closest I've gotten is:

List<Node> childNodes = (List<Node>) entityManager.createQuery("select n from Node n JOIN n.t_node_t_node t where n.id = " + parent_id).getResultList();

which returns the exception: Could not resolve property t_node_t_node

¿Fue útil?

Solución

Database column t_node_t_node cannot be used in JPQL query. JPQL queries operate to entities and their persistent attributes, not with the database tables and columns.

Likely your entity is roughly as follows:

@Entity
public class Node {
    @Id private Long id;

    @ManyToOne
    Node parent;

    @OneToMany(mappedBy = "parent")
    private List<Node> nodes;
...
}

When id of parent is given, child nodes can be queries as follows:

Long parentId = 1L;
Query q = em.createQuery("SELECT n FROM Node n WHERE n.parent.id =  :parentId");
q.setParameter("parentId", parentId);
List<Node> childNodes = q.getResultList();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top