JPA return value to Optional<List<T>> depends on SpringFramework version

JPA return value to Optional<List<T>> depends on SpringFramework version

spring boot
2.2.5.RELEASE

If spring boot is 2.2.5.RELEASE, jpa will be spring-data-jpa-2.2.5.RELEASE.jar.

Create a JPARepository with this version and create a method with Optional<List<T>> as the return value.

Then, if there are 0 cases, Optional.empty() will be returned.

spring boot
2.4.1

As you can see in the reference site below, Optional.empty() is returned even in 2.4.1.

At this time, spring-data-jpa-2.4.2.jar.

spring boot
2.4.2

Upgrade the version to 2.4.2, which is spring-data-jpa-2.4.3.jar.

Create a JPARepository with this version and create a method with Optional<List<T>> as the return value.

@Query(value = "select id from employee where id = :id ", nativeQuery = true)
Optional<List<Integer>> findByIdx(@Param("id") Integer id);

Then the return value is Optional[[]], which wraps the size()=0 instance of List with Optional, which changes the behavior. Normally, I think the current behavior is correct.

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.

In the case of a single return value, null consideration is necessary, but in the case of a method that assumes multiple returns in a List, the List is never null.

return value

error:Optional<List<T>>

correct:List<T>

// error
@Query(value = "select id from employee where id = :id ", nativeQuery = true)
Optional<List<Integer>> findByIdx(@Param("id") Integer id);
// correct
@Query(value = "select id from employee where id = :id ", nativeQuery = true)
List<Integer> findByIdx(@Param("id") Integer id);

Reference Site

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

コメント

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