0
votes

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

1

1 Answers

0
votes

You could include the code that may throw the exception in a try/catch statement and specify that you don't want rollback for this specific exception:

public static final int DEFAULT_VALUE_WHEN_GET_LAST_ITEM_FAILED = 1;
...
@Transactional(rollbackFor = ExpectedException.class)
public int getSomeValue(){

    try {
      MyObj obj = repo.getLastItem(); // this failed because not items in table, so I need here null   
      if (obj != null) {          
          return calculatedValue();
        }                     
    }
    catch(ExpectedException e){  
       //TODO exception logging
    }

    return DEFAULT_VALUE_WHEN_LAST_ITEM_FAILED;

}