如果发生故障,我如何使用JPA Transaction Manager进行提交和回滚

时间:2019-04-11 21:23:14

标签: java hibernate transactions spring-data-jpa

我有persistence.xml

<persistence-unit name="user_per_unit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.example.User</class>
<class>com.example.Order</class>
<class>com.example.Package</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.hbm2ddl.auto" value="validate" />
    <property name="hibernate.jdbc.batch_size" value="100" />
    <property name="hibernate.order_inserts" value="true" />
    <property name="hibernate.order_updates" value="true" />
    <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>

applicationContext.xml

<jpa:repositories base-package="com.example.user.repository" entity-manager-factory-ref="userEntityManagerFactory" transaction-manager-ref="userTransactionManager"/>

<bean id="userEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName"    value="user_per_unit" />
    <property name="dataSource"             ref="userDataSource" />
    <property name="jpaVendorAdapter"       ref="jpaVendorAdapter" />
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.format_sql">false</prop>
        </props>
    </property>
</bean>

<bean id="userTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="userEntityManagerFactory" />
</bean>

<bean id="userDataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="${driver}" />
    <property name="url" value="${url}" />
    <property name="username" value="${username}" />
    <property name="password" value="${password}" />
    <property name="initialSize" value="${size}" />
    <property name="maxTotal" value="${maxtotal}" />
    <property name="maxIdle" value="${maxidle}" />
    <property name="minIdle" value="${minidle}" />
</bean>

在我的class

@Autowired
private ApplicationContext applicationContext;
private JpaTransactionManager userTransactionManager;

userTransactionManager = (JpaTransactionManager) applicationContext.getBean("userTransactionManager");

如果出现问题,如何使用userTransactionManager进行提交和回滚。

0 个答案:

没有答案