1

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?

user1409534
  • 2,140
  • 4
  • 27
  • 33
  • Let's keep the discussion on the Hibernate discourse forum: https://discourse.hibernate.org/t/hibernate-scrollableresults-without-transaction/5491/4 – Christian Beikov Jun 30 '21 at 17:38

0 Answers0