交易回滚在春季不起作用

时间:2020-07-20 21:32:33

标签: java spring spring-data-jpa transactions rollback

基本上,我有一个Sampleapiclass类,其中一些文件被检索到列表中,并且该列表被循环,并为每个文件调用performAction。如果文件验证失败,我希望事务回滚。问题是,我尝试使用回滚进行注释,但是即使一个文件验证失败,事务也不会滚动bak.eg。文件1成功插入,文件2失败,但是文件1在数据库中。知道有什么问题吗?

作为附加说明,Sampleapiclass是从main方法初始化的,也许它可以做些什么? f.eks:来自主要班级

class MainClass
{
   
    public static void main(String[] args)
    {
        ApplContext ctx = new ClassPathxmlApplicationContext("application-context.xml");
        MainClass app = ctx.getBean(MainClass.class);
        app.run(args);
    }
    void run()
    {
          Sampleapiclass api = new Sampleapiclass();
          DaoClass dao = new Sampleapiclass();
          api.apimethod(dao)
    }
}


class Sampleapiclass
{
    
    void apimethod(Dao daoclass)
    {
        serviceClass serviceClass = new ServiceCLass(daoclass);
        List<String> files = filesFromSomewhere
        for (String file: filesFromSomewhere)
        {
            try
             {
                serviceClass.performAction(file);
             }
            catch(Exception e)
            {

            }
        }
    }
}


class serviceClass
{
    private final Dao daoclass;
    public serviceClass(DaoClass daoclass) 
     {
        this.daoclass = daoclass;
    }

    @Transactional(rollbackFor=Exception.class)
    void performAction(String file) throws CustomException
    {
        dovalidation(file); // this method can throw CustomExeption if validation fails
        daoclass.insert(file)
    }
    dovalidation(String file) throws CustomExeption
    {
    if (file.endsWith("somethng") throw new CustomExeption();
    }
}       

class dao
{
    void insert(String file)
    {
    getNamedParameterJdbcTemplate().update(parameters);
    }
}

应用程序内容的内容:

<bean class="Configbean class />
<bean id="dataSource" class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
    <property name="url" value="${main.db.uri}"/>
    <property name="username" value="${main.db.username}"/>
    <property name="password" value="${main.db.password}"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="transactionManager" ref="transactionManager" />
</bean>

1 个答案:

答案 0 :(得分:1)

问题是@Transactional与AOP一起使用。 AOP不适用于inclass方法调用(由于代理)。尝试在您的@Transactional内抛出一个异常,以使其正常工作或在您的类之外也标记为@Transaction(propagation = Propagation.SUPPORTS)

的外部调用方法

也不要忘记@EnableTransactionManagement类上的@Configuration

有用的资源https://javamondays.com/spring-transactions-explained/