diff --git a/spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/support/SimpleJpaRepositoryUnitTests.java b/spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/support/SimpleJpaRepositoryUnitTests.java index 59532d7f41..ab1f286bd3 100644 --- a/spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/support/SimpleJpaRepositoryUnitTests.java +++ b/spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/support/SimpleJpaRepositoryUnitTests.java @@ -26,11 +26,13 @@ import jakarta.persistence.TypedQuery; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.metamodel.SingularAttribute; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.stream.Stream; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -80,6 +82,7 @@ class SimpleJpaRepositoryUnitTests { @Mock CrudMethodMetadata metadata; @Mock EntityGraph entityGraph; @Mock org.springframework.data.jpa.repository.EntityGraph entityGraphAnnotation; + @Mock SingularAttribute idAttribute; @BeforeEach void setUp() { @@ -262,4 +265,38 @@ static Stream modifyingMethods() { private static String formatName(Method method) { return method.toString().replaceAll("public ", "").replaceAll(SimpleJpaRepository.class.getName() + ".", ""); } + + @Test // GH-4134 + @SuppressWarnings({"unchecked"}) + void existsByIdReturnsTrueWhenEntityExists() { + + when(information.getIdAttribute()).thenReturn(idAttribute); + when(information.getEntityName()).thenReturn("User"); + when(information.getIdAttributeNames()).thenReturn(List.of("id")); + when(information.hasCompositeId()).thenReturn(false); + when(em.createQuery(anyString(), eq(Long.class))).thenReturn(countQuery); + when(countQuery.getSingleResult()).thenReturn(1L); + + boolean result = repo.existsById(1); + + verify(countQuery).getSingleResult(); + assertThat(result).isTrue(); + } + + @Test // GH-4134 + @SuppressWarnings({"unchecked"}) + void existsByIdReturnsFalseWhenEntityDoesNotExist() { + + when(information.getIdAttribute()).thenReturn(idAttribute); + when(information.getEntityName()).thenReturn("User"); + when(information.getIdAttributeNames()).thenReturn(List.of("id")); + when(information.hasCompositeId()).thenReturn(false); + when(em.createQuery(anyString(), eq(Long.class))).thenReturn(countQuery); + when(countQuery.getSingleResult()).thenReturn(0L); + + boolean result = repo.existsById(1); + + verify(countQuery).getSingleResult(); + assertThat(result).isFalse(); + } }