JPA getResultStream() vs getResultList()

1.8k Views Asked by At

I have a method that executes a query:

EntityGraph<TypeA> fetch = em.createEntityGraph(TypeA.class);
Subgraph<TypeB> fetchTypeB = fetch.addSubgraph("typeB", TypeB.class);
fetchTypeB.addSubgraph("typeC", TypeC.class);

Set<TypeA> result = em.createQuery(
    "SELECT a FROM TypeA a " +
    "   LEFT JOIN a.b b " +
    "   LEFT JOIN b.c c " +
    "WHERE {...}", TypeA.class)
.setParameter(...)
.setHint("javax.persistence.loadgraph", fetch)
.getResultStream()
.collect(Collectors.toSet());

return result;

I want the method to return a Set. Here I am using .getResultStream().collect(Collectors.toSet());. I add some data to the database manually and then call the method. The result is correct. Next, I add some more values using an API. I check the database, everything is as expected, but when I call the method, I only get the values I inserted manually.

Now, I make a single change - I use getResultList() and transform it to a HashSet:

EntityGraph<TypeA> fetch = em.createEntityGraph(TypeA.class);
Subgraph<TypeB> fetchTypeB = fetch.addSubgraph("typeB", TypeB.class);
fetchTypeB.addSubgraph("typeC", TypeC.class);

List<TypeA> result = em.createQuery(
    "SELECT a FROM TypeA a " +
    "   LEFT JOIN a.b b " +
    "   LEFT JOIN b.c c " +
    "WHERE {...}", TypeA.class)
.setParameter(...)
.setHint("javax.persistence.loadgraph", fetch)
.getResultList();

return new HashSet<>(result);

And now I get all values, including the ones added via API. If I change back to the first version, same problem occurs as before. Does anyone have any idea what could cause this?

0

There are 0 best solutions below