3

I want to save multiple records in DB using Hibernate.I m succeeded in that.But thinking my approach is wrong.Since If records increases it will create performance prob.

I want to store in DB like,

FirstName          LastName   
FNameABC           LNameCC         
FNamePQR           LNameDD         
FNameXYZ           LNameEE 

I stored the above values in DB as,

Iterator itr = list.Iterator();
while(itr.hasNext()) {
   Test t = (Test)itr.next();
   dbEntity.setFirstName(t.setFirstName());
   dbEntity.setLastName(t.setLastName());
   session.beginTransaction();
   session.save(dbEntity);
   session.getTransaction().commit();
   session.close();
}  

Here I'm saving the value in the seession inside a loop. So every time for each record it will call beginTransaction(), save(), commit(). Is there any better approach ?

1
  • are you sure every insert should be done in a separate transaction? Commented Jan 19, 2012 at 12:56

2 Answers 2

3

Please take a look at this page: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html

You should open a transaction, save the entities (in the loop), at the end commit the transaction and close the session. As suggested you can have a counter while looping and flash/clean the session after certain number is reached - periodically.

Sign up to request clarification or add additional context in comments.

2 Comments

Using this approach with large numbers of entities it will be necessary to flush and clear the session at regular intervals. Dirty checking a large number of entities quickly becomes a bottleneck.
Depends on the case, number of entities, number of open sessions ... Sometimes does not worth to implement complex solution if the cases won't happen. My answer was only for the specified situation. I agree that in extreme cases different approach should be considered.
2

You don't choose to start and commit a transaction based on technical or performance considerations. You choose to do it based on what you consider should be done atomically, coherently, and in isolation to the other transactions. Read http://en.wikipedia.org/wiki/ACID.

If you want to make sure that all the inserts either succeed or fail, but that you shouldn't be in a state where half succeed and the other half fail, then your transaction should encapsulate all the inserts: you start the transaction before the first one, and commit it after the last one.

If, on the contrary, you want each insert to be done in its own transaction, and for example be able to catch the exception if one fails but coninue inserting the others, then each insert should be done in its own transaction, like you're doing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.