0

I have two entities :

A:

class A {

 @Id
 Long id;

 @OneToMany(fetch = FetchType.LAZY)
 List<B> listOfB;
}

and class B :

class B {

 @Id
 Long id;

 @ManyToOne(fetch = FetchType.LAZY)
 A a;
}

now in my spring data repo I'm creating a query like :

@Query("SELECT a FROM A a INNER JOIN a.listOfB b WHERE b.id = :id")

The problem is, that the query is executed and returns some A objects, but when I want to access the listOfB I'm getting a NullPointerException ...

A a = aRepository.findByOwnQuery(id);
a.getListOfB().size(); -> NullPointerException
Bart
  • 201
  • 1
  • 4
  • 13

1 Answers1

-1

The NullPointerException could be because you are fetching your child listOfB Lazily in your parent class A.

Try JOIN FETCH like so

@Query("SELECT a FROM A a JOIN FETCH a.listOfB b WHERE b.id = :id")
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
  • With such contruction I'm getting the `ArgumentException` error `Encountered "b" at ... but expected: [",", "GROUP", "HAVING", "INNER", "JOIN", "LEFT", "ORDER", "WHERE", ]`. – Bart Aug 14 '17 at 11:43
  • Are you sure this exception is because of the single change i suggested.?Because my change doesn't change the argument. It only changes the strategy to fetch to children. Please cross check. – Abdullah Khan Aug 14 '17 at 11:50
  • Yep, because the previous query executes fine but returns null for the list. – Bart Aug 14 '17 at 11:53
  • 3
    The JPA spec doesn't allow use the 'b' defined on a fetch join clause within the query. You would have to create a separate join for the query to use in the where clause. – Chris Aug 14 '17 at 17:41
  • @Chris Thats something i didn't know. Can you post some reference. – Abdullah Khan Aug 15 '17 at 06:04
  • I don't have a link to the spec, but the definition in "4.4.5.3 Fetch Joins" of jpa 2.1 does not include aliases. Its posted in other answers elsewhere as well though https://stackoverflow.com/a/16693590/496099 – Chris Aug 15 '17 at 18:44