I am using Spring Data JPA and trying to stream results from the database using the Stream API. However, I need to enforce a timeout for the query execution. I’ve tried several approaches, but none of them seem to be working for streaming queries. Here are the things I have tried so far:
JPA Query Timeout (javax.persistence.query.timeout)
I tried setting the query timeout hint on the @Query annotation:
@QueryHints({@QueryHint(name = "jakarta.persistence.query.timeout", value = "1000")})
@Query("select e from Entity e where e.someField >= :value")
Stream<Entity> streamByFieldGreaterThanOrEqual(@Param("value") long value);
This works fine for standard queries but does not seem to work with streaming queries, as they fetch results lazily.
Transaction Timeout: I also tried using Spring’s TransactionTemplate to set a timeout for the entire transaction:
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.setTimeout(1); // Timeout in seconds
transactionTemplate.execute(status -> {
Stream<Entity> stream = repository.streamByFieldGreaterThanOrEqual(value);
stream.forEach(entity -> { });
return null;
});
But the stream execution continues even after the specified timeout.
Question:
Is there a reliable way to enforce a query timeout specifically for streaming queries in Spring Data JPA? Note – I’m aware of Guava’s SimpleTimeLimiter to enforce a timeout at the method level.
I would appreciate any insights or suggestions on how to handle this scenario effectively!
2