Вопрос

I've tried to do this query but it still selects every child even though I just want the ones with the specific name. How would I achieve that?

@NamedQuery(name="Parent.getChildrenWithName",
                query="SELECT p FROM Parent p "
                        + "join p.children c "
                        + "where c.name = :childName")
public class Parent
{
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "parentId")
    private List<Child> children;
}

public class Child
{
    @Column(name = "ChildName")
    private String childName;

    private int parentId;
}

Just read this on http://docs.oracle.com/javaee/6/tutorial/doc/bnbtl.html#bnbtr:

Expressions cannot navigate beyond (or further qualify) relationship fields that are collections. In the syntax of an expression, a collection-valued field is a terminal symbol. Because the teams field is a collection, the WHERE clause cannot specify p.teams.city (an illegal expression).

This is my code that fetches the result:

TypedQuery<Parent> query = em.createNamedQuery("Parent.getChildrenWithName", Parent.class);
query.setParameter("childName", "Daniel");
Parent parent = query.getSingleResult();

But the question remains :)

Нет правильного решения

Другие советы

Change your code like below,

    TypedQuery<Parent> query = em.createNamedQuery("Parent.getChildrenWithName", Parent.class);
    query.setParameter("childName", "Daniel");
    Parent parent = query.getSingleResult();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top