I have a piece of code that iterate a ScrollableResults and do some calculation on each element. The iteration is surrounded by transaction.
EntityTransaction transaction = emf.createEntityManager().getTransaction();
transaction.begin();
ScrollableResults scrollableResults = em.unwrap(Session.class).createQuery("my select query").scroll();
while (scrollableResults.next()){
MyEntity entity= (MyEntity) scrollableResults.get(0);
someCalculation(entity);
}
transaction.commit();
em.close();
I use ScrollableResults since I don't want to load all items to memory on the other hand I don't want to keep the transaction open for a long time since the iteration may take some time. I omitted the begin and commit transaction and I was still able to iterate the resultSet. What is the best solution for this kind of scenario ? Should I keep the transaction open for a long time or not using transaction at all?