From e48bcf6e841c0c6d9eb6478798b9d7fce67d31b8 Mon Sep 17 00:00:00 2001 From: Sebastien Deleuze Date: Tue, 26 Jun 2018 11:07:19 +0200 Subject: [PATCH] =?UTF-8?q?DATACMNS-1346=20-=20Add=20a=20findByIdOrNull(?= =?UTF-8?q?=E2=80=A6)=20extension=20to=20CrudRepository.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In Kotlin, it is idiomatic to deal with return value that could have or not a result with nullable types since they are natively supported by the language. This commit adds CrudRepository.findByIdOrNull(…) variant to CrudRepository#findById that returns T? instead of Optional. Original pull request: #299. --- .../repository/CrudRepositoryExtensions.kt | 10 ++++++++ .../CrudRepositoryExtensionsTests.kt | 25 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 src/main/kotlin/org/springframework/data/repository/CrudRepositoryExtensions.kt create mode 100644 src/test/kotlin/org/springframework/data/repository/CrudRepositoryExtensionsTests.kt diff --git a/src/main/kotlin/org/springframework/data/repository/CrudRepositoryExtensions.kt b/src/main/kotlin/org/springframework/data/repository/CrudRepositoryExtensions.kt new file mode 100644 index 000000000..7c3bfb2a8 --- /dev/null +++ b/src/main/kotlin/org/springframework/data/repository/CrudRepositoryExtensions.kt @@ -0,0 +1,10 @@ +package org.springframework.data.repository + +/** + * Retrieves an entity by its id. + * + * @param id the entity id. + * @return the entity with the given id or `null` if none found + * @author Sebastien Deleuze + */ +fun CrudRepository.findByIdOrNull(id: ID): T? = findById(id).orElse(null) diff --git a/src/test/kotlin/org/springframework/data/repository/CrudRepositoryExtensionsTests.kt b/src/test/kotlin/org/springframework/data/repository/CrudRepositoryExtensionsTests.kt new file mode 100644 index 000000000..6f4d262e1 --- /dev/null +++ b/src/test/kotlin/org/springframework/data/repository/CrudRepositoryExtensionsTests.kt @@ -0,0 +1,25 @@ +package org.springframework.data.repository + +import com.nhaarman.mockito_kotlin.verify +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Answers +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner +import org.springframework.data.repository.sample.User + +/** + * @author Sebastien Deleuze + */ +@RunWith(MockitoJUnitRunner::class) +class CrudRepositoryExtensionsTests { + + @Mock(answer = Answers.RETURNS_MOCKS) + lateinit var repository: CrudRepository + + @Test + fun `CrudRepository#findByIdOrNull() extension should call its Java counterpart`() { + repository.findByIdOrNull("foo") + verify(repository).findById("foo") + } +}