2016-10-04 16 views
1

データベース操作にspring-data-jpaリポジトリを使用しています。リポジトリ内のすべてのメソッドのオブジェクトがデータベースに存在しない場合は例外をスローしたい例えば、私ははcustomerIdとpaymentIdに基づいてすべての注文を照会するOrderRepositoryspringデータの検索メソッドに例外をスローする方法jpa

findByCustomerAndPayment(Customer customer, Payment payment); 

で次のような方法を考えてみましょう。上記のクエリでは、両方のオブジェクトが必要です。しかし、spring-data-restは、cutomerIdがデータベースに存在しないことを示していればnullを返します。オブジェクトがデータベースに存在しない場合、Spring-data-restが例外をスローすることを期待しています。

これを行うには?

答えて

2

Java 8を使用している場合は、Optional<Order>をリポジトリ・メソッドの戻り値の型として使用できます。リポジトリメソッドが空の場合は、Optionalを呼び出すと、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); 
} 

IncorrectResultSizeDataAccessExceptionはです

として編集しますは、throws宣言の必要はありません - 私はそれを修正しました。

関連する問題