I'm learning SpringBoot2.0
with Java8
.
And I followed some blog-making tutorial example.
The tutorial source code is:
@GetMapping("/{id}/edit")
public String edit(@PathVariable Long id, Model model) {
model.addAttribute("categoryDto", categoryService.findOne(id));
return "category/edit";
}
But this code is throwing this error:
categoryService.findOne(id)
I'm thinking about changing the JPA findOne()
method to Optional< S >
How to solve that?
More info:
This is the categoryService method:
public Category findOne(Long id) {
return categoryRepository.findOne(id);
}
This question is related to
java
spring
spring-data-jpa
I always write a default method "findByIdOrError" in widely used CrudRepository repos/interfaces.
@Repository
public interface RequestRepository extends CrudRepository<Request, Integer> {
default Request findByIdOrError(Integer id) {
return findById(id).orElseThrow(EntityNotFoundException::new);
}
}
Indeed, in the latest version of Spring Data, findOne returns an optional. If you want to retrieve the object from the Optional, you can simply use get() on the Optional. First of all though, a repository should return the optional to a service, which then handles the case in which the optional is empty. afterwards, the service should return the object to the controller.
Optional
api provides methods for getting the values. You can check isPresent()
for the presence of the value and then make a call to get()
or you can make a call to get()
chained with orElse()
and provide a default value.
The last thing you can try doing is using @Query()
over a custom method.
The method has been renamed to findById(…)
returning an Optional
so that you have to handle absence yourself:
Optional<Foo> result = repository.findById(…);
result.ifPresent(it -> …); // do something with the value if present
result.map(it -> …); // map the value if present
Foo foo = result.orElse(null); // if you want to continue just like before
Source: Stackoverflow.com