How to insert multiple rows into database using hibernate?

后端 未结 3 2035
逝去的感伤
逝去的感伤 2020-12-08 17:40

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

相关标签:
3条回答
  • 2020-12-08 18:05

    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/.

    0 讨论(0)
  • 2020-12-08 18:14

    With the save() method in a session, Hibernate couples the object to a row and this relation remains while the session remains active. Therefore, if you use the same object, you actually update the existing row. The solution is to construct a new object for every row. In this case:

    for (String item : items)
    {
      Feature feature = new Feature();
      feature.setName(item);
      session.save(feature);
    }
    
    0 讨论(0)
  • 2020-12-08 18:15
    session.merge(object);
    session.flush();
    session.clear();
    
    0 讨论(0)
提交回复
热议问题