Spring data JPA findOne() returns null

Asked

Viewed 1,310 times

0

I am developing an application using Spring MVC, with spring data jpa in the persistence layer.

When I try to do a search using the method findOne (or findById) returns always null.

I already checked in the database and there is the registered record with the indicated Id.

Method call:

public Atividade findById(short id) {
    return atividades.findOne(id);
}

Error while trying to search:

java.lang.Nullpointerexception: null at br.com.transformare.service.Activitiesdeservice.findById(Activitiesdeservice.java:32)

Can anyone tell me if it would be some mistake in my code or some spring data bug?

  • 1

    Put more snippets of the code. Only with this you informed and difficult to understand. Preferably copy the method that is calling "activities.findOne(id)" and also where it shows the error (Activityjava:32)

  • 2

    It seems that your "activities" object has not been instantiated/injected. As well noted by @Doug, enter the full code of the class.

2 answers

0

The id is probably not receiving the value passed by the request. In this case, use the annotation @PathVariable to indicate that the id will come in the request URI. In the current version of Spring Data, the findOne method is not compatible with what you showed. Give preference to findById with orelse.

Example:

public Atividade findById(@PathVariable short id) {
    return atividades.findById(id).orElse(null);
}

Do not forget to also map the request above the method, for example: @GetMapping("/{id}")

-1

Create a repository with the following call in the database

Atividade findById(short id)

and use her place of findOne

Tip: work id as long and not as short

  • ID like int would also be bad?

  • It depends a lot on the application. If it is a very large application where there will be thousands of records, the ideal would be to use Long. Here’s the difference between the two. int goes from -2.147.483.648 to 2.147.483.647 Long from -9.223.372.036.854.775.808 to 9.223.372.036.854.775.807 .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.