0

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?

syydi
  • 119
  • 2
  • 13
  • From the docs of `.stream()` method: `You should call java.util.stream.Stream.close() after processing the stream so that the underlying resources are deallocated right away.` You could attempt this – XtremeBaumer Jun 21 '22 at 13:24
  • Stream javadoc says: `Most stream instances do not actually need to be closed after use, as they are backed by collections, arrays, or generating functions, which require no special resource management. Generally, only streams whose source is an IO channel, will require closing`. I still went on to try out your theory and discovered nothing new. – syydi Jun 21 '22 at 14:08
  • Interesting. It might have to do with the specifics of how you are adding the values through the API. It would probably help if you included the minimum code necessary. At the very least, are you sure the API has committed the transaction before you execute the query? Also, if it is a bug, the exact version of Hibernate might be useful. – Nikos Paraskevopoulos Jun 22 '22 at 07:50

0 Answers0