java - How to properly handle empty resultset with Hibernate and Spring Boot -
i have spring app using hibernate , spring data jpa's crudrepository
. seems work if data queried exists in database. however, if there query returns no result, crudrepository
returns null
, nullpointerexception
. example http://localhost:8080/api/id=3
if there row id 3 in database works fine. if there isn't row id of 3 fails a:
there unexpected error (type=internal server error, status=500)
on client side , nullpointerexception
on server side.
what proper way of dealing simple case of "no results" query?
inspect return value, if it's not null
, return representation of 200 ok
response. otherwise, return 404 not found
. in end, have controller like:
@requestmapping(...) public responseentity<?> getone(...) { something = repository.findone(...); if (something == null) return responseentity.notfound().build(); return responseentity.ok(something); }
can refactor preceding code incorporate java 8's
optional<t>
, jb nizet mentioned in comments. basically, optional<t>
container may or may not hold value of type t
. can use type return type of spring data jpa methods, following: public interface somethingrepository extends crudrepository<something, long> { optional<something> findbyid(long id); }
then define 1 exception 404 not found
:
@responsestatus(httpstatus.not_found) public class notfoundexception extends runtimeexception {}
if throw exception of type notfoundexception
in controllers, spring mvc's exception resolver catch exception , convert 404 not found
http response.
finally controller like:
@requestmapping(...) public getone(...) { return repository.findbyid(id).orelsethrow(notfoundexception::new); }
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, can check out rest in practice book.
Comments
Post a Comment