Tyl*_*rry 2 java spring transactional
我有一个迭代事件列表并将它们保存到表中的进程.如果某个特定事件抛出异常,我需要能够使用数据库回滚该事件的事务,而不会影响其他事件的流程.
为此,我有以下设置:
public class EventService
{
public void processEvents()
{
List<Event> events = getEvents();
foreach(Event event : events)
{
try
{
processEvent(event);
}
catch(Exception e)
{
// log the exception and continue processing additional events
}
}
}
@Transactional
public void processEvent(Event event)
{
// Process event and insert rows into database
// Some event will throw a runtime exception
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果抛出异常,则不会回滚事件.
有没有办法实现我在这里要做的事情?
您需要使用Propagation.REQUIRES_NEW和rollbackFor = Exception.class定义您的流程事件,如下所示:
@Transactional(propagation=Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
public void processEvent(Event event)
{
// Process event and insert rows into database
// Some event will throw a runtime exception
}
Run Code Online (Sandbox Code Playgroud)
如果在同一个类中调用方法,Spring AOP没有机会拦截该方法.因此,@Transactional注释被忽略.尝试将processEvent方法移动到Spring注入的另一个类.