Batch inserts with @Transactional annotation

In my spring application i want to insert almost 1500 records in database in one go. I am using Spring 4.X and plain hibernate in backend. In my service layer i use @Transactional annotation. Now while inserting the records after somepoint i get outofmemory error. After searching on internet i found out that we can use something similar to this

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
    if ( i % 20 == 0 ) { //20, same as the JDBC batch size
        //flush a batch of inserts and release memory:
        session.flush();
        session.clear();
    }
}

tx.commit();
session.close();

However, above code they are using sessionFactory and transaction manually and use flush and clear on session object and do i a manual commit.

In my case i do not want to use above code, i want to use @Transactional annotation to make this work.

Please suggest

I do not want to use session factory and transaction object manually. ....@transactional should do it all

Answers


If you want change from BMT(Bean Managment Transaction) to CMT (Container Transaction Managment), your snippet on code will became:

@Transactional(propagation=Propagation.REQUIRES_NEW)
public void saveCustomers(){
    for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
    }
}

The container will flush all entities when the method will end. Now I want to ask you, Why Do you nees to need each 20 entities?


Need Your Help

How Do I get 'font-weight: lighter' to work in Google Chrome?

css fonts cross-browser

There doesn't appear to be any difference between 'font-weight: normal' and 'font-weight: bold' in Google Chrome (and probably Safari). Has anyone found a way to invoke the 'font-weight: thinner' in

WebBrowser compatibility issue with website

c# browser compatibility

(new WebBrowser()).Version.ToString() // returns 9.0.8112.16421