JPAの戻り値をOptional<List<T>>にするとSpringFrameworkのバージョンによって変わる
spring boot |
---|
2.2.5.RELEASE |
spring bootが2.2.5.RELEASEだとjpaは、spring-data-jpa-2.2.5.RELEASE.jarになります。
このバージョンでJPARepository作成し、Optional<List<T>>を戻り値とするメソッドを作成します。
すると0件の場合、Optional.empty()が返ってきます。
spring boot |
---|
2.4.1 |
下の参考サイトにもありますが、2.4.1でもOptional.empty()が返ってくるようです。
この時、spring-data-jpa-2.4.2.jarになります。
spring boot |
---|
2.4.2 |
2.4.2にバージョンをアップすると、spring-data-jpa-2.4.3.jarになります。
このバージョンでJPARepository作成し、Optional<List<T>>を戻り値とするメソッドを作成します。
@Query(value = "select id from employee where id = :id ", nativeQuery = true) Optional<List<Integer>> findByIdx(@Param("id") Integer id);
すると戻り値は、Optional[[]]を返します。Listのsize()=0のインスタンスをOptionalでラップすることになり挙動が変わります。普通に考えると今の動きが正解だと思います。
Alternatively, query methods can choose not to use a wrapper type at all. The absence of a query result is then indicated by returning null. Repository methods returning collections, collection alternatives, wrappers, and streams are guaranteed never to return null but rather the corresponding empty representation.
1件の戻り値の場合はnull考慮が必要ですが、Listで複数件返ってくる想定のメソッドの場合、リストがnullになることはないようです。size()=0のリストが返ってくるようで、null考慮は不要だそうです。
戻り値
誤:Optional<List<T>>
正:List<T>
// 誤 @Query(value = "select id from employee where id = :id ", nativeQuery = true) Optional<List<Integer>> findByIdx(@Param("id") Integer id); // 正 @Query(value = "select id from employee where id = :id ", nativeQuery = true) List<Integer> findByIdx(@Param("id") Integer id);
参考サイト
KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES6),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^
コメント