我正在使用SpringFramework 3,Hibernate 4和MySQL 5与jpa。我的测试代码看起来像...
@Repository
public class TestRepositoryImpl implements TestRepository {
@PersistenceContext
private EntityManager em;
@Override
@Transactional
public void insertBulk() {
Item it;
for(int i= 0; i<1000;i++) {
it = new Item();
it.setPrice(Math.random()*100);
em.persist(it);
}
}
}
我的Spring配置
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="application" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
我的persistence.xml文件
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="application" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.springapp.test.domain.Item</class>
<class>com.springapp.test.domain.Order</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="false" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/testdb" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.jdbc.batch_size" value="20" />
</properties>
</persistence-unit>
</persistence>
当我运行我的代码时,它会触发1000次插入查询而不是50次插入查询。问题出在哪里?请帮我使用Hibernate在JPA中进行批量插入。