2

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 :)

Cœur
  • 37,241
  • 25
  • 195
  • 267
Lucas Arrefelt
  • 3,879
  • 5
  • 41
  • 71
  • You have a named query 'Parent.getChildrenWithName' which other part of your code are your using it. Can you paste the code which refers this named query ? – Jay Mar 06 '14 at 16:00
  • edited my question with that code! – Lucas Arrefelt Mar 06 '14 at 16:19
  • You query on Child.name (`... where c.name = :childName`) but your entity has mapped column `ChildName` to `persnr`. Perhaps you should query with `c.persnr` instead. Maybe you have a property `name` on the class and you actually query against it. – Tasos P. Mar 06 '14 at 16:29

1 Answers1

0

Change your code like below,

    TypedQuery<Parent> query = em.createNamedQuery("Parent.getChildrenWithName", Parent.class);
    query.setParameter("childName", "Daniel");
    Parent parent = query.getSingleResult();
Jay
  • 9,189
  • 12
  • 56
  • 96