在 Hibernate 中快速插入许多实体

我想使用 Hibernate 4.2 将 170.000 个实体的列表插入到我本地安装的 MySQL 8.0 数据库中。目前我正在通过 Session#save 方法执行此操作。但是插入那么多实体会持续很长时间。那么是否有可能更快地做到这一点?


for (Agagf x : list) {

    create(x);

}


// ------------------------


    public static void create(Object obj) throws DatabaseException {

        Session hsession = null;


        try {

            hsession = SqlDataHibernateUtil.getSessionFactory().openSession();

            Transaction htransaction = hsession.beginTransaction();

            hsession.save(obj);

            htransaction.commit();

        } catch (HibernateException ex) {

            throw new DatabaseException(ex);

        } finally {

            if (hsession != null)

                hsession.close();

        }

    }


慕无忌1623718
浏览 90回答 1
1回答

GCT1015

Hibernate 页面上有这篇文章:http:&nbsp;//docs.jboss.org/hibernate/orm/4.2/manual/en-US/html/ch15.html根据他们的说法,你需要这样的东西:create(list);// ------------------------public static void create(List<Object> objList) throws DatabaseException {&nbsp; Session hsession = null;&nbsp; try {&nbsp; &nbsp; hsession = SqlDataHibernateUtil.getSessionFactory().openSession();&nbsp; &nbsp; Transaction htransaction = hsession.beginTransaction();&nbsp; &nbsp; int count = 0;&nbsp; &nbsp; for(Agagf x: objList) {&nbsp; &nbsp; &nbsp; &nbsp; hsession.save(obj);&nbsp; &nbsp; &nbsp; &nbsp; if ( ++count % 20 == 0 ) { //20, same as the JDBC batch size&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //flush a batch of inserts and release memory:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hsession.flush();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hsession.clear();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count = 0;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; } catch (HibernateException ex) {&nbsp; &nbsp; throw new DatabaseException(ex);&nbsp; } finally {&nbsp; &nbsp; htransaction.commit();&nbsp; &nbsp; if (hsession != null) {&nbsp; &nbsp; &nbsp; hsession.close();&nbsp; &nbsp; }&nbsp; }}此外,启用批处理的配置:如果您正在进行批处理,则需要启用 JDBC 批处理。如果您想获得最佳性能,这是绝对必要的。将 JDBC 批处理大小设置为合理的数字(例如 10-50):hibernate.jdbc.batch_size 20编辑:在你的情况下,使用批量大小来更好地适应你的体积。请记住在配置和 if 语句中为刷新设置相同的大小。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java