How to properly close and open a Hibernate session?

前端 未结 2 407
我寻月下人不归
我寻月下人不归 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: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();
        }
    }
    

提交回复
热议问题