My code has several JPA repository method call. I fetch data and aggregate it. But I want to do that in an asynchronous way. So, I am trying to use CompletableFeature. But I am getting the below error:
failed to lazily initialize a collection of X: package_name.CollectionName, could not initialize proxy - no Session
My code: public CompletableFuture aggregateDownloadableData(params...) {
return CompletableFuture.supplyAsync(() -> {
//my code to manipulate data sets here
//
//
return Boolean.TRUE;
}
});
This code works fine if I remove CompletableFeature usage from this method, but not using this.
I also tried providing my own ExecutorService:
public CompletableFuture<Boolean> aggregateDownloadableData(params...) {
ExecutorService executor = Executors.newFixedThreadPool(2);
return CompletableFuture.supplyAsync(() -> {
//my code to manipulate data sets here
//
//
return Boolean.TRUE;
}
}, executor);
}
But this doesn't work either.
Any suggestion, please?
N.B: I don't want to load eagerly
The reason for this exception is that, when run asynchronously, the Hibernate session will be closed before the lazy loaded collection can be initialized. Hence
no Sessionmessage.There are several solutions you can try: