Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Object Relational Mapping and the fly likes Basic Hibernate question regarding Bulk Insertions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Basic Hibernate question regarding Bulk Insertions" Watch "Basic Hibernate question regarding Bulk Insertions" New topic

Basic Hibernate question regarding Bulk Insertions

Roger Haynie

Joined: Jan 21, 2005
Posts: 3

I am working on an application what uses Hibernate to populate (initialize)a DB with a large web of interconnected objects. It has several many-to-many link tables, etc.. I don't have a problem with mapping the objects, but how to cleanly handle massive number of insertions using Hibernate's API.

I have followed the advice of the Hibernate docs and have a sythetic key assigned from a sequence in the DB. Now when I insert a duplicate object Hibernate has no problem inserting a new row in the DB with a new sequence id. If I give the Business Key a unique constraint an exception is thrown. Now I don't like the idea of finding out about a duplicate through an exception.

I was wondering what is the standard way that this situation is handled. Is it to first issue a Query (or get()) on the root object and every single member of its collections on each insert to make sure they don't exist and if they do reuse that object?

I know this is probably a very newbee question, but any guidance would be greatly appreciated.

David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
This thread covers the downside of doing a query for a duplicate before performing the insert instead of using a unique index and responding to the exception. Long story short, there's a race condition that forces you to respond to the exception anyway, so you may as well put the duplicate-handling code in one place.
I agree. Here's the link:
subject: Basic Hibernate question regarding Bulk Insertions
It's not a secret anymore!