Anoop LL
Anoop LL

Reputation: 1575

How to batch execute SQL query using Hibernate session

I am using the below set of code for an update:

private void updateAvatarPath(Integer param1, String param2, String param3, boolean param4){

        Transaction avatarUpdatePathTransaction = session.beginTransaction();


        String updateQuery = "query goes here with param";

        Query query = session.createSQLQuery(updateQuery);
        query.executeUpdate();

        avatarUpdatePathTransaction.commit();
        session.flush();
    }

This function is being called from a loop. So this takes time to update since for each loop it's hitting the DB. Instead of hitting DB every time, to increase the performance I am planning to execute it as batches. But have no idea how to do it.

session.doWork() is one of the solutions which I got. I want to know any other option available to do it.

Upvotes: 2

Views: 299

Answers (1)

Guillaume
Guillaume

Reputation: 14656

You should move Transaction avatarUpdatePathTransaction = session.beginTransaction(); before the start of your loop and avatarUpdatePathTransaction.commit(); after the end of your loop.

The recommended pattern is to have one session per "unit of work", in your case this seems to be modifying multiple entities in a single session/transaction.

The session.flush(); is not necessary I think, committing the transaction should flush the session

Upvotes: 2

Related Questions