2015-05-20 80 views
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; 
    } 




} 
+0

請參閱我編輯的答案。您是否嘗試使用'profileSQL'參數來檢查MySQL驅動程序是否重寫語句? –

回答

1

很可能是你實際使用的配料,它只是休眠打印SQL進行每個語句。

要對此進行檢查,(如果你想看到的約束變量org.hibernate.type和跟蹤級別)啓用org.hibernate包DEBUG日誌級別,然後檢查以下日誌中出現:

  • 重用批處理語句

  • 執行批量大小

如果數大於1被印刷爲執行批量大小,那麼你正在使用批處理。

針對MySQL,爲了確保MySQL驅動程序重寫插入語句,在連接url中啓用profileSQL參數,如here所述。

NOTE:如果使用IDENTITY ID生成器,則JDBC批處理爲disabled

我還建議您考慮將hibernate.order_updates設置爲true,以改進更新語句的批處理。關於這個Hibernate調優的一個很好的總結描述here