Batch Insertions with Hibernate & Spring

前端 未结 3 793
名媛妹妹
名媛妹妹 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.

    0 讨论(0)
  • 2021-02-06 13:42

    You only need the bit with flushing and clearing the session. Leave transaction management to Spring. Use sessionFactory.getCurrentSession() to reach the session that Spring has already opened for you. Also, Spring's recent recommmendation is to avoid HibernateTemplate and work directly with Hibernate's API. Inject SessionFactory to your dao-bean.

    0 讨论(0)
  • 2021-02-06 13:49

    I would refactor parse in a way it doesn't call save directly but takes some callback from service layer. Service layer would pass its transactional method with save call as this callback.

    It may not work exactly as decribed in your case but from this short description this would be something I'd try.

    0 讨论(0)
提交回复
热议问题