spring-data-jpa @RestController @Repository Option

2019-08-27 01:39发布

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条回答
该账号已被封号
2楼-- · 2019-08-27 01:53

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.

查看更多
登录 后发表回答