问题
My @RestController
@GetMapping("/projects/{project_id}")
public Project getProjectById(@PathVariable(value = "project_id") UUID projectId) {
return projectRepository.findById(projectId).orElseThrow(Util.notFound(projectId));
}
My projectRepository is
@Repository
public interface ProjectRepository extends PagingAndSortingRepository<Project, UUID> {
}
public class Util {
static Supplier<ResourceNotFoundException> notFound(UUID msg) {
log.error(msg + " not found");
return () -> new ResourceNotFoundException(msg + " not found");
}
}
When i do GET {{host}}/projects/{{projId1}}
, it return the result. However, in the log, it show .
org.hibernate.SQL: select project0_.id as id1_4_0_, proje...
o.h.type.descriptor.sql.BasicBinder: binding parameter [1] as [OTHER]
ERROR: projectId not found .
How is it orElseThrow always got executed, after the data has been returned?
回答1:
Fix your Util
public class Util {
static Supplier<ResourceNotFoundException> notFound(UUID msg) {
return () -> {
log.error(msg + " not found");
return new ResourceNotFoundException(msg + " not found");
};
}
}
You need to log only in case you actually throw it.
来源:https://stackoverflow.com/questions/56180844/spring-data-jpa-restcontroller-repository-optional-strange-behavior