How to properly close and open a Hibernate session?

前端 未结 2 406
我寻月下人不归
我寻月下人不归 2021-01-26 19:13

I have the following method that inserts a large batch of records every few seconds. After some time of running I get errors like the following:

ERROR: C

相关标签:
2条回答
  • 2021-01-26 19:53

    Rather make a generic method for any object type and pass the object. Add logic of any List too.

    public void save(Object obj) {
        Session session = null;
        Transaction transaction = null;
        try {
            session = sessionFactory.getCurrentSession();
            transaction = session.beginTransaction();
            session.save(obj);
            session.flush();
            transaction.commit();
        } catch (JDBCException jde) {
            logger.fatal("Error occured in database communication", jde);
            transaction.rollback();
            throw new RuntimeException(jde);
        } finally {
            if (session.isOpen()) {
                session.close();
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-26 19:56
        Transaction tx = session.beginTransaction();
        try {
            for (int i = 0; i < mesages.size(); i++) {
                Message message = messages.get(i);
                session.save(message);
                if (i % 75 == 0) { 
                    // flush a batch of inserts and release memory:
                    session.flush();
                    session.clear();
                }
            }
            tx.commit();
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            tx.rollBack();
        }finally{
            session.close();
        }
    }
    
    0 讨论(0)
提交回复
热议问题