vishnu
vishnu

Reputation: 165

Can I execute batch of queries using jpa/hibernate in a single shot?

Here is a sample code. sourceFileItemNo and entityDplStatus are array of some values.

Query query; 
for(int i = 0 ;(sourceFileItemNo!=null && i< sourceFileItemNo.length); i++){
    Object[] parameters = {entityDplStatus[i],"1",sourceFileItemNo[i]};
    String queryString = "UPDATE GtcEntityDetailsValue c SET c.dplStatus=?1 where c.referenceNo=?2 and c.itemNo=?3";
    query = manager.createQuery(queryString);
    query = setQueryParameters(query, parameters);
    query.executeUpdate();
}

Here in this case we are updating the details each time in each iteration. Does JPA provides provision to add the queries to a list or something and execute all the queries in a single shot just like old connection statement execute batch?

Upvotes: 0

Views: 307

Answers (1)

Suvansh
Suvansh

Reputation: 264

Yes you can easily do it using hibernate,pass the list of objects with updated values that you want to persist, then just do:

 private void updteRecord(List<Records> records){
    int batchSize=10;
    for(int i=0;i<records.size();i++)
    {
        getSession().saveOrUpdate(records.get(i));

        if(i%batchSize==0)
        {
            getSession().flush();
            getSession().clear();
        }
    }
}

The List of records you are feeding to this method should contain the values you need to upodate.

Upvotes: 1

Related Questions