spring-data-jpa @RestController @Repository可选的奇怪行为

时间:2019-05-17 06:35:06

标签: java spring-boot optional spring-restcontroller spring-repositories

我的@RestController

@GetMapping("/projects/{project_id}")
public Project getProjectById(@PathVariable(value = "project_id") UUID projectId) {
    return projectRepository.findById(projectId).orElseThrow(Util.notFound(projectId));
}

我的projectRepository是

@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");
    }
}

当我执行GET {{host}}/projects/{{projId1}}时,它返回结果。但是,在日志中显示。

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 . 

返回数据后如何执行ElseThrow?

1 个答案:

答案 0 :(得分:3)

修复您的Util

public class Util {
    static Supplier<ResourceNotFoundException> notFound(UUID msg) {
        return () -> {
            log.error(msg + " not found");
            return new ResourceNotFoundException(msg + " not found");
        };
    }
}

仅在实际抛出时才需要登录。