2017-09-23 35 views
0

在我的代碼中,update方法可能會返回null,並且它會影響調用此方法的事務。Spring Data:在update中返回null將回滾事務

正如我所知只拋出運行時異常或用戶指定檢查的異常將觸發回滾操作,那麼返回null也會觸發它呢?

服務1

public class Service1 { 

    @Autowired 
    private Service2 service2; 

    @Autowried 
    private Service1Repository service1Repository; 

    @Transactional 
    public Entity1 update(Entity1 entity) { 
     service1Repository.update(entity); 

     // if this method return null, above update will rollback. Otherwise, it will be executed success. 
     service2.update(entity.getId()); 

     return entity; 
    } 
} 

服務2:

public class Service2 { 
    @Autowired 
    private Service2Repository service2Repository; 

    @Transactional 
    public Entity2 update(Integer id) { 
     Entity2 entity = service2Repository.findOne(id); 

     // No need to update HIDDEN status entity 
     if (Status.HIDDEN.equals(entity.getStatus())) { 
      return null; 
     } 

     entity.setOtherAttribute("xyz"); 
     service2Repository.update(entity); 

     return entity; 
    } 
} 

回答

0

返回nullService2.update()方法不會回滾數據庫事務,因爲它是正常執行代碼。

此外,如春天documentation說:

任何RuntimeException的觸發回滾,但是任何checked異常不會。

+0

是的,我也這麼認爲,但這實際上發生在我的代碼中,所以我只是想確認這種情況並非如此。 – sgyyz

+0

什麼沒有按預期與您的代碼一起工作? – lzagkaretos

+0

我的意思是如果我的Service2.update()得到執行,並且如果它返回null,Service1.update()將不會更新任何數據。它看起來像service1Repository.update()將回滾數據。 – sgyyz