gpt4 book ai didi

java - 无法在已检查的异常上回滚事务

转载 作者:行者123 更新时间:2023-11-30 02:14:21 25 4
gpt4 key购买 nike

如果抛出 IllegalStateException,以下服务将无法回滚持久保存 Foo 对象,尽管我已将 MyServiceImpl 标记为 @Transactional (rollbackFor = IllegalStateException.class)。我还尝试将 upload 方法标记为 @Transactional(rollbackFor = IllegalStateException.class),但问题仍然存在,如果 会发生 IllegalStateException :

@Service
@Transactional
public class MyServiceImpl implements IMyService{
@Autowired
private IFooService fooService;
@Autowired
private IBarService barService;

@Override
@Transactional(rollbackFor = IllegalStateException.class, propagation = Propagation.REQUIRED)
public void upload(Foo foo, Bar bar) throws IllegalStateException{
try{
fooService.addFoo(foo);//foo object is persisted in the DB whether the upload call would succeed or fail (i.e. throws an IllegalStateException)
if(!check(bar))
throw new IllegalStateException("The object bar is not valid");
barService.addBar();
} catch(Exception e){
e.printStackTrace();
}
}

//This method simply validates the input Bar object
private boolean check(Bar bar){
//source code omitted
}
}

@Service
@Transactional
public class FooServiceImpl implements IFooService{
@Autowired
private IFooDao fooDao;

@Override
@Transactional(propagation = Propagation.REQUIRED)
public void addFoo(final Foo foo){
fooDao.addFoo(foo);
}
}

@Service
@Transactional
public class BarServiceImpl implements IBarService{
@Autowired
private IBarDao barDao;

@Override
@Transactional(propagation = Propagation.REQUIRED)
public void addBar(final Bar bar){
barDao.addBar(bar);
}
}

public class Foo implements Serializable{
private int id;
//source code omitted
}

public class Bar implements Serializable{
private int id;
private Foo foo;
//source code omitted
}

我的数据源配置:

@Bean(name="dataSource")
public ComboPooledDataSource getDataSource() throws PropertyVetoException{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(env.getProperty("db.driverClass"));
dataSource.setJdbcUrl(env.getProperty("db.jdbcUrl"));
dataSource.setUser(env.getProperty("db.user"));
dataSource.setPassword(env.getProperty("db.password"));
dataSource.setMaxPoolSize(50);
dataSource.setMinPoolSize(5);
dataSource.setMaxConnectionAge(1800);
dataSource.setMaxIdleTime(1800);
dataSource.setAutoCommitOnClose(false);
dataSource.setInitialPoolSize(5);
return dataSource;
}

请问我该如何解决这个问题?

更新:更新源代码并添加try/catch子句。

最佳答案

看起来addFoo在它自己的转换中执行。

你可以用它来注释

@Transactional(propagation = Propagation.REQUIRED)

这样,在这种情况下它将使用相同的事务,并且如果从其他地方调用而没有 @Transactional 注释,则创建一个新事务。

关于java - 无法在已检查的异常上回滚事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49052011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com