Poor batch insert performance when inserting different objects

Description

Batch insert works nicely when you only have one object to insert:

for (int i = 0; i < 20; i++) {
Book book = new Book();
dao.save(book);
}

Provided that the batch size in Hibernate is set to 20, Hibernate will correctly batch up to 20 insert statements and execute the batch at the end.

However, the following code example gives a different result:

for (int i = 0; i < 20; i++) {
Book book = new Book();
Author author = new Author();
dao.save(book);
dao.save(author);
}

In this case Hibernate will execute every single insert as a separate batch query. The result is 40 different insert statements fired at the database instead of 2.

In the org.hibernate.jdbc.AbstractBatcher class I found a probable reason for this behaviour. The prepareBatchStatement method checks if the current sql is the same as the sql of the previous statement. If so, the previous prepared statement will be reused. This is never the case for my 2nd example above, where Hibernate continuously switches between "insert into Book..." and "insert into Author" statements.

Would it be possible to cache more than one prepared statement?

Environment

None

Activity

Show:
Anders Wallgren
July 12, 2010, 9:27 PM
Koen Verrecken
July 13, 2010, 1:30 PM

Nice, that will do the job. Is there a reason why this is not the default behaviour?

Also, I did a search on google for this property and only found similar articles and forum threads about people having the same problem. Perhaps it would be nice to add this to the hibernate documentation in Chapter 13. Batch processing

Anders Wallgren
July 14, 2010, 4:59 AM

might be one reason it's not enabled by default.

Assignee

Unassigned

Reporter

Koen Verrecken

Fix versions

None

Labels

None

backPortable

None

Suitable for new contributors

None

Requires Release Note

None

Pull Request

None

backportDecision

None

Components

Affects versions

Priority

Major
Configure