Hibernate EntityManager persist()和数据库往返计数 [英] Hibernate EntityManager persist() and database round trip count
问题描述
@现在我正在使用entitymanager将对象实体列表插入到数据库中。交易
公共无效insertBatch(列表与LT; EntityObject>○){
为(INT I = 0; I< o.size();我++){
em.persist(O);
if(o.size%100 == 0){//等于JDBC批量大小
em.flush();
em.clear();
}
}
}
当我监视sql声明将此添加到application-context中
< property name =jpaVendorAdapter>
< bean class =org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter>
< property name =showSqlvalue =true/>
< / bean>
< / property>
结果如下
休眠:插入到TABLE(FIELD1,FIELD2)值
休眠(?,?):插入到TABLE(FIELD1,FIELD2)值$ b(?,?) $ b ...
...
... //直到100行。
Hibernate:insert into TABLE(FIELD1,FIELD2)values(?,?)
My问题是。
这是否意味着每次我调用这个方法时,它都会与数据库进行100次往返,或者它只执行1次往返,否则呢?
任何答案或洞察力将被理解的。
感谢。
如果你处于休眠JPA需要配料,尝试设置
<属性名= hibernate.jdbc.batch_size 值=100/>
按照JPA规范:
受管实体X将在
事务提交或之前进入数据库,或作为刷新操作的结果。
所以,冲水数据库往返。
顺便说一句,如果你正在使用Hibernate,JPA与弹簧(交易),那么春天将管理事务为你。您不必调用em.flush(理想情况下)
Right now I am using entitymanager to insert list of object entity to database with my dao using code like this.
@Transaction
public void insertBatch(List<EntityObject> o){
for(int i=0;i<o.size();i++){
em.persist(o);
if(o.size % 100 == 0){ //equal to JDBC batch size
em.flush();
em.clear();
}
}
}
And when I monitor the sql statement by add this into application-context
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
</bean>
</property>
And the result in console will look like this
Hibernate: insert into TABLE (FIELD1, FIELD2) values (?, ?)
Hibernate: insert into TABLE (FIELD1, FIELD2) values (?, ?)
...
...
...//untill reach 100 lines.
Hibernate: insert into TABLE (FIELD1, FIELD2) values (?, ?)
My question is. Does it mean that each time when i call this method it will do round trip with database for 100 times,or is it do only 1 round trip, or else?
Any answer or insight would be appreciate.
Thanks.
If you need batching in hibernate jpa,try setting
<property name="hibernate.jdbc.batch_size" value="100" />
As per JPA spec:
The managed entity X will be entered into the database at or before transaction commit or as a result of the flush operation.
So, flush is the database round trip.
BTW if you are using hibernate-jpa with spring (transaction), then spring will manage transactions for you. You need not be calling em.flush (ideally)
这篇关于Hibernate EntityManager persist()和数据库往返计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!