spring-data-jpa @RestController @Repository Optional strange behavior

非 Y 不嫁゛ 提交于 2019-12-24 20:25:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!