使用JpaTransactionManager嵌套的事务行为

时间:2014-12-11 08:41:03

标签: java spring hibernate transactions

我想用spring应用程序实现嵌套事务行为。 以下是我的Spring配置。                   

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"></property>
    <property name="persistenceUnitName" value="hibernatePersistenceUnit" />
    <property name="dataSource" ref="dataSource" />
     <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
             <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/>
        </bean>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="dataSource" ref="dataSource" />
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    <property name="nestedTransactionAllowed" value="true" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager"  proxy-target-class="true" />

我也有两个春季托管豆。

public class Bean1{

 @Autowired
private TesttableRepository testtableRepository;

@Autowired
private Bean2 bean2;

 @Transactional
 public void testMethod()  {
    Testtable entry = new Testtable();
    entry.setDescription("ABC");
    entry = testtableRepository.save(entry);


try{
 bean2.testNestedTransactional();
}catch(DataIntegrityViolationException e){
 e.printStackTrace();

}
    entry.setDescription("ABCEEEEEEEEEEEEEEEEEEEEEEEEE");
    testtableRepository.save(entry)
}

}

public class Bean2{

 @Autowired
 private TesttableRepository testtableRepository;

@Transactional(propagation = Propagation.NESTED)
public void testNestedTransactional()  {
    Testtable entry1 = new Testtable();
    entry1.setDescription("SSSS");
    testtableRepository.save(entry1);
}
}

这是我的实体课程。

@Entity(name="testtable")
public class Testtable implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(unique=true, nullable=false)
private int testid;

@Column(length=10)
private String description;

public Testtable() {
}

public int getTestid() {
    return this.testid;
}

public void setTestid(int testid) {
    this.testid = testid;
}

public String getDescription() {
    return this.description;
}

public void setDescription(String description) {
    this.description = description;
}

}

由于bean1对象中的testMethod()在保存“ABCEEEEEEEEEEEEEEEEEEEEEEEEEEE”(最大描述长度字段设置为10)时失败,我想回滚Bean2.But中testNestedTransactional()所做的更改,但配置对我来说不起作用。有什么想法吗?

0 个答案:

没有答案