Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate batch insert - how flush works?

I need to insert a lot of data in a database using hibernate, i was looking at batch insert from hibernate, what i am using is similar to the example on the manual:

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();

but i see that flush doesn't write the data on the database. Reading about it, if the code is inside a transaction then nothing will be committed to the database until the transaction performs a commit.

So what is the need to use flush/clear ? seems useless, if the data are not written on the database then they are in memory.

How can i force hibernate to write data in the database?

Thanks

like image 275
res1 Avatar asked Feb 02 '26 05:02

res1


2 Answers

The data is sent to the database, and is not in memory anymore. It's just not made definitively persistent until the transaction commit. It's exacltly the same as if you executes the following sequences of statements in any database tool:

begin;
insert into ...
insert into ...
insert into ...
// here, three inserts have been done on the database. But they will only be made
// definitively persistent at commit time
...
commit;

The flush consists in executing the insert statements.

The commit consists in executing the commit statement.

like image 191
JB Nizet Avatar answered Feb 03 '26 19:02

JB Nizet


The data will be written to the database, but according to the transaction isolation level you will not see them (in other transactions) until the transaction is committed.

Use some sql statement logger, that prints the statmentes that are transported over the database connection, then you will see that the statmentes are send to the database.

like image 28
Ralph Avatar answered Feb 03 '26 20:02

Ralph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!