MayoMan
MayoMan

Reputation: 4917

Batch inserts/updates with hibernate

I am using the class AbstractSimpleGenericDao similar to the form in http://code.google.com/p/struts2-jquery/source/browse/showcase-grid/src/com/jgeppert/struts2/jquery/grid/showcase/dao/AbstractSimpleGenericDao.java?r=322

MyDAO extends this class. I have 1000s of objects I want hibernate to persist. Do I call MyDAO.save( object ) on each one. This seems very inefficient to me. Does this cause a DB hit each time? Is there any way to insert lots of objects at the same time?s

Upvotes: 1

Views: 2615

Answers (1)

Alex Barnes
Alex Barnes

Reputation: 7218

You do indeed have to call save on each item which you want to persist to the database. It's worth bearing in mind that Hibernate is an ORM. It can be used for batch inserts but it's often not the most efficient way of doing it.

It's certainly worth having a read of this chapter of the Hibernate manual if you haven't already. There are some useful tips in there about keeping your session small to avoid lots of dirty checking etc. If you just insert 1000s of objects without evicting any previous objects the operations will get slower and slower as Hibernate has to dirty check more and more objects.

The way in which Hibernate actually performs the insert is designed to be as efficient as possible. Inserts can be batched to take advantage of database optimizations. It's worth bearing in mind that if you use an identify based generator e.g. on MySQL you will lose any batching advantages. This is because Hibernate has to actually do the insert in order to generate your identifier at the point that you insert the object to the session.

You can implement an alternative identifier generation strategy to ensure that you don't need to do this. One possibility might be a table which stores the current highest identifier for each entity. Hibernate can then request identifiers from this table in suitably sized batches.

If you find Hibernate slow you could always fall back to plain old JDBC for this task.

Upvotes: 4

Related Questions