hibernatejpaopenjpajpa-2.1

Spring JPA - No transaction set autocommit 'true'


Is there any way to autocommit using JPA without transaction?

persistence.xml

<persistence-unit name="mytest" transaction-type="RESOURCE_LOCAL">
    <properties>
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
    </properties>
</persistence-unit>

data-config.xml

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="mytest" />
        <property name="dataSource" ref="myDataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="database" value="ORACLE" />
            </bean>
        </property>
        <property name="jpaPropertyMap">
            <map>
<entry key="hibernate.format_sql" value="false" />
                <entry key="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
                <entry key="hibernate.jdbc.fetch_size" value="0" />
                <entry key="hibernate.jdbc.batch_size" value="0" />
                <entry key="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy" />
            </map>
        </property>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <qualifier value="mytest"/>
    </bean>

CODE

for(User user: users) {
    entityManager.merge(user);
    entityManager.flush();
}

But I am not able to see the commit until the session is terminated. I want to commit record by record.


Solution

  • No, there is no autocommit in JPA, it doesn't make much sense either, since every change to an entity is a change that eventually goes to the database. With an autocommit, every single change to a property would be a transaction. That is a very special requirement, that doesn't qualify as a feature candidate for JPA.

    But all you need to do is to wrap a transaction around entityManager.merge(user);