can you tell me how can I run transaction only for some block of code? I have service functions with @Transactional, and from them I call repository functions where I execute queries. But when query failed, it also failed service function because transaction must be ended. So how could I return null value when repository function failed? I need catch null value when failed, and continue some logic. My Code:
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
}
}
}
EDIT I'll tried @davidxxx 's answer and I got this error :
Transaction was marked for rollback only; cannot commit; nested exception is javax.persistence.PersistenceException: org.hibernate.TransactionException: Transaction was marked for rollback only; cannot commit