Skip to content

Commit

Permalink
Switch to Query.getSingleResultOrNull().
Browse files Browse the repository at this point in the history
We now use getSingleResultOrNull() to avoid NoResultException handling.

Closes #3701
  • Loading branch information
mp911de committed Dec 11, 2024
1 parent 58264a5 commit 9f3bac8
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
package org.springframework.data.jpa.repository.query;

import jakarta.persistence.EntityManager;
import jakarta.persistence.NoResultException;
import jakarta.persistence.Query;
import jakarta.persistence.StoredProcedureQuery;

Expand Down Expand Up @@ -87,13 +86,7 @@ public Object execute(AbstractJpaQuery query, JpaParametersParameterAccessor acc
Assert.notNull(query, "AbstractJpaQuery must not be null");
Assert.notNull(accessor, "JpaParametersParameterAccessor must not be null");

Object result;

try {
result = doExecute(query, accessor);
} catch (NoResultException e) {
return null;
}
Object result = doExecute(query, accessor);

if (result == null) {
return null;
Expand Down Expand Up @@ -221,7 +214,7 @@ static class SingleEntityExecution extends JpaQueryExecution {
@Override
protected Object doExecute(AbstractJpaQuery query, JpaParametersParameterAccessor accessor) {

return query.createQuery(accessor).getSingleResult();
return query.createQuery(accessor).getSingleResultOrNull();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@

import jakarta.persistence.EntityManager;
import jakarta.persistence.LockModeType;
import jakarta.persistence.NoResultException;
import jakarta.persistence.Parameter;
import jakarta.persistence.Query;
import jakarta.persistence.TypedQuery;
Expand Down Expand Up @@ -433,12 +432,7 @@ public Page<T> findAll(Pageable pageable) {

@Override
public Optional<T> findOne(Specification<T> spec) {

try {
return Optional.of(getQuery(spec, Sort.unsorted()).setMaxResults(2).getSingleResult());
} catch (NoResultException e) {
return Optional.empty();
}
return Optional.ofNullable(getQuery(spec, Sort.unsorted()).setMaxResults(2).getSingleResultOrNull());
}

@Override
Expand Down Expand Up @@ -540,13 +534,10 @@ private <S extends T, R> R doFindBy(Specification<T> spec, Class<T> domainClass,
@Override
public <S extends T> Optional<S> findOne(Example<S> example) {

try {
return Optional
.of(getQuery(new ExampleSpecification<>(example, escapeCharacter), example.getProbeType(), Sort.unsorted())
.setMaxResults(2).getSingleResult());
} catch (NoResultException e) {
return Optional.empty();
}
TypedQuery<S> query = getQuery(new ExampleSpecification<>(example, escapeCharacter), example.getProbeType(),
Sort.unsorted()).setMaxResults(2);

return Optional.ofNullable(query.getSingleResultOrNull());
}

@Override
Expand Down

0 comments on commit 9f3bac8

Please sign in to comment.