Domanda

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.

È stato utile?

Soluzione

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)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top