JPAの戻り値をOptional<List<T>>にするとSpringFrameworkのバージョンによって変わる

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);

参考サイト

Spring Data JPA - Reference Documentation
Optional for Empty List in Repository Layer Returns Optional.empty . How do I change it to return Optional[[]]
I have a JPA Query like this. PersonRepository.java public Optional<List<PersonEntity>> findByStatus(int status); Person...
Spring Data JPA - Reference Documentation

コメント

株式会社CONFRAGE ITソリューション事業部をもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む

タイトルとURLをコピーしました