【问题标题】:Hibernate batch insert休眠批量插入
【发布时间】:2015-08-01 20:24:49
【问题描述】:

这是我在数据库中插入批处理的代码

  @Override
  public void addMultiple(){

    session = get_session();
  tx = session.beginTransaction();
 for ( int i=0; i<100; i++ ) {
 Person person = new Person();
 person.setName("oll"+i);
 session.save(person);
 if( i % 20 == 0 ) { // Same as the JDBC batch size
    //flush a batch of inserts and release memory:
    session.flush();
    session.clear();
   }
}
tx.commit();
session.close();
}

这是我的hibernate.cfg.xml 文件

 <property  name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.jdbc.batch_versioned_data">true</property>
<property name="hibernate.jdbc.batch_size">20</property>
<property name="hibernate.order_inserts">true</property>
<property name="hibernate.current_session_context_class">thread</property>

但插入操作后我可以看到查询打印在控制台是

  Hibernate: insert into Person (name) values (?)
  Hibernate: insert into Person (name) values (?)
  Hibernate: insert into Person (name) values (?)
  Hibernate: insert into Person (name) values (?)
  Hibernate: insert into Person (name) values (?)
  Hibernate: insert into Person (name) values (?)
  Hibernate: insert into Person (name) values (?)
  Hibernate: insert into Person (name) values (?)
  Hibernate: insert into Person (name) values (?)
  Hibernate: insert into Person (name) values (?)
  Hibernate: insert into Person (name) values (?)

这意味着它不会插入批处理。我的实体没有标识符生成。那么问题是什么?为什么我不能插入批处理?

我的实体类是

  @Entity
  public class Person {

   @Id
   public String name;

    public String getName() {
    return name;
     }

  public void setName(String name) {
    this.name = name;
  }




 }

【问题讨论】:

  • 请看我编辑的答案。您是否尝试使用profileSQL 参数检查 MySQL 驱动程序是否重写语句?

标签: hibernate jdbc


【解决方案1】:

很可能您实际上正在使用批处理,只是 Hibernate 为每个语句打印 sql。

要检查这一点,请为org.hibernate 包启用 DEBUG 日志级别(如果您想查看绑定变量,请为org.hibernate.type 启用 TRACE 级别),然后检查日志中是否出现以下内容:

  • 重用批处理语句

  • 执行批量大小

如果为已执行的批处理大小打印大于 1 的数字,那么您正在使用批处理。

特定于 MySQL,为确保 MySQL 驱动程序重写插入语句,请在连接 url 中启用profileSQL 参数,如here 所述。

注意:如果使用 IDENTITY id 生成器,则 JDBC 批处理为 disabled

我还建议您考虑将hibernate.order_updates 设置为true,以改进更新语句的批处理。 here 描述了有关此 Hibernate 调整的一个很好的总结。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 2012-11-18
    • 2012-08-14
    • 1970-01-01
    相关资源
    最近更新 更多