2016-10-04 47 views
1

我正在使用spring-data-jpa存儲庫進行數據庫操作。我想拋出異常如果對象不存在於我的倉庫中的所有方法的數據庫中。例如考慮OrderRepository如何在彈簧數據中的搜索方法拋出異常jpa

findByCustomerAndPayment(Customer customer, Payment payment); 

我想查詢基於客戶ID和paymentId所有訂單以下方法。這兩個對象在上面的查詢中都是需要的。但是,如果我給cutomerId在數據庫中不存在,spring-data-rest將返回null。如果對象不存在於數據庫中,我希望spring-data-rest引發異常。

如何實現這一目標?

回答

2

如果您使用的是Java 8,則可以使用Optional<Order>作爲存儲庫方法的返回類型。如果存儲庫方法返回一個空的Optional調用get它會拋出一個NoSuchElementException。否則,如果沒有結果,則不支持通過存儲庫方法拋出異常。

try { 
    Optional<Order> result = repository.findByCustomerAndPayment(customer,payment); 
    Order order = result.get(); 
} catch(NoSuchElementException e) { 
    // do something with the exception 
} 
3

您可以自定義的倉庫實現象下面這樣:

public interface OrderRepositoryCustom { 
    Order findByCustomerAndPaymentRequired(Customer customer, Payment payment); 
} 

public class OrderRepositoryImpl implements OrderRepositoryCustom { 

    @Autowired 
    OrderRepository orderRepository; 

    @Override 
    public Order findByCustomerAndPaymentRequired(Customer customer, Payment payment) { 
     Order o = orderRepository.findByCustomerAndPayment(customer, payment); 
     if(o == null) { 
      throw new IncorrectResultSizeDataAccessException(1); 
     } 
     return o; 
    } 

} 

OrderRepository接口應該擴展定製:

public interface OrderRepository extends CrudRepository<Order, Long>, OrderRepositoryCustom { 
    Order findByCustomerAndPayment(Customer customer, Payment payment); 
} 

編輯

由於IncorrectResultSizeDataAccessExceptionRuntimeException,那麼不需要throws聲明 - 我解決了這個問題。