【发布时间】:2018-05-23 13:53:03
【问题描述】:
你能告诉我如何只为某些代码块运行事务吗?我有 @Transactional 的服务函数,我从它们调用存储库函数来执行查询。但是当查询失败时,它也使服务功能失败,因为必须结束事务。那么当存储库函数失败时我怎么能返回空值呢?失败时我需要捕获空值,并继续一些逻辑。我的代码:
public class SomeService{
@Autowired
SomeRepository repo;
@Transactional
public int getSomeValue(){
MyObj obj = repo.getLastItem(); // this failed because not items in table, so I need here null
if (obj != null) {
//some calculations
return [calculatedValue]
} else {
return 1
}
}
}
编辑 我会尝试@davidxxx 的答案,我得到了这个错误:
事务被标记为仅回滚;不能提交;嵌套异常是 javax.persistence.PersistenceException: org.hibernate.TransactionException: 事务被标记为仅回滚;无法提交
【问题讨论】:
标签: java spring transactions