简体   繁体   中英

OpenJPA fetching entity with a lazy collection

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM