简体   繁体   中英

Spring return null when transaction rollback

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

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM