Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to insert a good amount of records in hibernate

I'm using hibernate + play! framework at work, is there a "best practice" on inserting a good amount of records using hibernate? They are around 6,000 to 10,000 per text file so I don't know if Hibernate is going to choke on the job or throw an exception.

Any suggestion let me know, let me know if I have to explain more

like image 209
allenskd Avatar asked Jan 03 '11 19:01

allenskd


People also ask

What is batch size in Hibernate?

batch_size , the Hibernate documentation recommends a value of between 5 and 30 but this value depends upon the application's needs. The Hibernate documentation's recommendation is suitable for most OLTP-like applications.

Which method is used to store data in table using Hibernate?

Hibernate Session save As the method name suggests, hibernate save() can be used to save entity to database.

How do you fetch all the records in a given table using Hibernate?

JPQL provides a simple and straightforward way to get all entities from a table. Our Hibernate session's createQuery() method receives a typed query string as the first argument and the entity's type as the second. We execute the query with a call to the getResultList() method which returns the results as a typed List.


1 Answers

Just some corrections of the codes in the answer of Kartoch.

According to Batch Procession, "The insert(), update() and delete() operations defined by the StatelessSession interface are considered to be direct database row-level operations. They result in the immediate execution of a SQL INSERT, UPDATE or DELETE respectively. They have different semantics to the save(), saveOrUpdate() and delete() operations defined by the Session interface."

No more save(), flush(), clear() for StatelessSession. The code should be like this :

StatelessSession session = sessionFactory.openStatelessSession();
Transaction tx = session.beginTransaction();

for ( int i=0; i<100000; i++ ) {
  Item item = new Item(.....);
  session.insert(item );
}    

tx.commit();
session.close();

Finally, Here is a discussion of the difference between the normal batch inserting and the StatelessSession insert : Using StatelessSession for Batch processing.

like image 98
Qianyue Avatar answered Oct 12 '22 12:10

Qianyue