这是我在数据库中插入批次的代码
@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
file
<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;
}
}
很可能您实际上正在使用批处理,只是 Hibernate 为每个语句打印 sql。
要检查这一点,请启用 DEBUG 日志级别org.hibernate
包(以及 TRACE 级别org.hibernate.type
如果您想查看绑定变量),请检查日志中是否出现以下内容:
如果执行的批处理大小打印的数字大于 1,则说明您正在使用批处理。
特定于 MySQL,为了确保 MySQL 驱动程序重写插入语句,启用profileSQL
连接 url 中的参数,如所述here https://stackoverflow.com/questions/21530112/no-matter-what-i-cant-batch-mysql-insert-statements-in-hibernate.
NOTE:JDBC 批处理是disabled http://vladmihalcea.com/hibernate-identity-sequence-and-table-sequence-generator/如果使用 IDENTITY id 生成器。
我还建议你考虑设置hibernate.order_updates
为 true,也可以改进更新语句的批处理。描述了有关 Hibernate 调整的一个很好的总结here http://vladmihalcea.com/how-to-batch-insert-and-update-statements-with-hibernate/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)