Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert multiple rows into database using hibernate?

Tags:

java

hibernate

I'm looping list and inserting into database , but its getting updating records one by one.finally i'm seeing in database last record of the list only.

input name : Linux,windows,mac

Session session = (Session) HibernateUtil.getSessionFactory().openSession();
String[] items = pi.getNewLicenseName().split(",");
for (String item : items)
{
feature.setName(item);
session.save(feature);
}
 session.getTransaction().commit();
 HibernateUtil.shutdown();

hibernate.cfg.xml:

<hibernate-configuration>

    <session-factory>


    <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="connection.url">jdbc:sqlserver://******</property>
    <property name="connection.username">*****</property>
    <property name="connection.password">*****</property>

    <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>


        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>


        <property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>

        <!-- Names the annotated entity class -->

         <mapping class="com.DAO.Feature"/>

    </session-factory>

Here three times get the loop and inserting into database.But somehow overwriting the values.Because i'm see the sql insert and update running in console.

Hibernate: insert into FEATURE (NAME) values (?)
Hibernate: update FEATURE set NAME=? where FEATURE_ID=?

Please help me to insert the multiple rows into database.

like image 920
user2848031 Avatar asked Dec 08 '13 20:12

user2848031


Video Answer


1 Answers

There's a very nice chapter about batch processing in the Hibernate docs.

Set the property

hibernate.jdbc.batch_size 20

Then use this code

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
    if ( i % 20 == 0 ) { //20, same as the JDBC batch size
        //flush a batch of inserts and release memory:
        session.flush();
        session.clear();
    }
}

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

Make sure you consider the implications for your id-generation strategy e.g. discussed here.

Update 2015-09-23

I finally found the time to sit down and write a detailed article at https://frightanic.com/software-development/jpa-batch-inserts/.

like image 134
Marcel Stör Avatar answered Oct 25 '22 12:10

Marcel Stör