2
這是我的代碼數據庫Hibernate的批量插入
@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驅動程序是否重寫語句? –