How to properly handle empty resultset with Hibernate and Spring Boot

后端 未结 2 2016
-上瘾入骨i
-上瘾入骨i 2021-02-09 18:10

I have a Spring app that is using Hibernate and the Spring Data JPA\'s CrudRepository. Everything seems to work properly if the data that was queried for exists in

相关标签:
2条回答
  • 2021-02-09 19:05

    None of the spring crud repository find methods throw an exception if no results are returned. They all return nulls. Since you are getting a null pointer exception on the server side you must be trying to perform an operation on the returned value without checking whether it's null first.

    0 讨论(0)
  • 2021-02-09 19:15

    Inspect the return value, if it's not null, return some representation of it as a 200 OK response. Otherwise, return a 404 Not Found. In the end, you would have a controller like:

    @RequestMapping(...)
    public ResponseEntity<?> getOne(...) {
        Something something = repository.findOne(...);
        if (something == null)
            return ResponseEntity.notFound().build();
    
        return ResponseEntity.ok(something);
    }
    


    You can refactor the preceding code to incorporate Java 8's Optional<T>, as JB Nizet mentioned in the comments. Basically, Optional<T> is just a container that may or may not hold a value of type T. You can use this type as the return type of Spring Data JPA methods, something like the following:

    public interface SomethingRepository extends CrudRepository<Something, Long> {
        Optional<Something> findById(Long id);
    }
    

    Then define one exception for 404 Not Found:

    @ResponseStatus(HttpStatus.NOT_FOUND)
    public class NotFoundException extends RuntimeException {}
    

    If you throw an exception of type NotFoundException in your controllers, Spring MVC's exception resolver would catch that exception and convert it to a 404 Not Found HTTP response.

    Finally your controller would be like:

    @RequestMapping(...)
    public Something getOne(...) {
        return repository.findById(id).orElseThrow(NotFoundException::new);
    }
    


    For more detailed discussions on:

    • Spring Data JPA's Optional<T> support, read here.
    • Spring MVC's exception resolvers, read here.
    • Java 8's Optional<T>, read here.
    • REST best practices, you can check out the REST in Practice book.
    0 讨论(0)
提交回复
热议问题