JpaRepository QueryByExample方法使用詳解


spring-data-jpa從1.12版本開始,JpaRepository繼承的接口由之前的CrudRepository,PagingAndSortingRepository改為了QueryByExampleExecutor,PagingAndSortingRepository。這其中的變化主要就是CrudRepository接口換成了QueryByExampleExecutor接口。

QueryByExampleExecutor接口用了Java 1.8增加的Optional 用以優雅的解決NullPointException 的問題。從而導致JpaRepository中之前類似於

 T findOne(ID id);

 

方法定義修改為

Optional<S> findOne(Example<S> example);

即傳參和回調分別改為了Example和Optional。因此方法使用與之前不同。

之前調用findOne方法只需簡單一行即可。

public User getOne(String id) {
     return userRepository.findOne(id);  
}

現在則需要先封裝成一個Exmple再傳參進行查詢。

public User getOne(String id) {
     User user = new User();
     user.setId(id);
     Example<User> userExample = Example.of(user);
     return userRepository.findOne(userExample).orElse(null); 
}

而且返回的是一個Optional類,關於Optional類具體的解釋就不貼出來了,以下是幾種關於Optional獲取實體類的實用方法。

  • 存在即返回, 無則提供默認值

    return user.orElse(null);  //而不是 return user.isPresent() ? user.get() : null;
    return user.orElse(UNKNOWN_USER);

     

  • 存在即返回, 無則由函數來產生

    return user.orElseGet(() -> fetchAUserFromDatabase()); //而不要 return user.isPresent() ? user: fetchAUserFromDatabase();

     

  • 存在才對它做點什么

    user.ifPresent(System.out::println);
     
    //而不要下邊那樣
    if (user.isPresent()) {
      System.out.println(user.get());
    }

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM