Batch Insertions with Hibernate & Spring

前端 未结 3 792
名媛妹妹
名媛妹妹 2021-02-06 12:54

My application is based on Hibernate 3.2 and Spring 2.5. Here is the transaction management related snippet from the application context:

  

        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-06 13:33

    For the batch insertion with hibernate, the best practice is StatelessSession, it doesn`t cache any states of your entity, you will not encounter OutOfMemory, the code like:

    if (books == null || books.isEmpty) {
        return;
    }
    StatelessSession session = getHibernateTemplate().getSessionFactory().openStatelessSession();
    Transaction tx = session.beginTransaction();
    
    for (Book each : books) {           
        session.insert(book);           
    }
    tx.commit();
    session.close();
    

    And the Transaction of StatelessSession is independent from the current transaction context.

提交回复
热议问题