Reputation: 201
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 ?
Upvotes: 3
Views: 16357
Reputation: 985
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.
Upvotes: 3
Reputation: 691635
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.
Upvotes: 2