Reputation: 385
I want to edit my User Class while passing the id and while returning user object to controller it is getting error such as "There was an unexpected error (type=Internal Server Error, status=500)".It is telling me to typecast to Optional.I don't know what to do.
UserService Class
public User editMyUser(int id) {
return userRepository.findById(id);
}
Controller Class
@RequestMapping("/edit-user")
public String editUser(@RequestParam int id, HttpServletRequest request) {
userService.deleteMyUser(id);
request.setAttribute("user", userService.editMyUser(id));
request.setAttribute("mode", "MODE_UPDATE");
return "welcome";
}
Upvotes: 1
Views: 428
Reputation: 1
I let u here the cofiguration of the interface for a rest service that is working rihg now
@Api(value = "empleados", description = "the empleados API")
public interface EmpleadosApi {
@ApiOperation(value = "Buscar empleados", notes = "", response = ResultadoBusquedaEmpleado.class, tags = {})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Búsqueda de empleados", response = ResultadoBusquedaEmpleado.class) })
@RequestMapping(value = "/empleados", method = RequestMethod.GET)
ResponseEntity<ResultadoBusquedaEmpleado> empleadosGet(
@ApiParam(value = "Nombre de empleado") @RequestParam(value = "nombre", required = false) String nombre)
}
Upvotes: -1
Reputation: 5354
This is how findById
looks like in the new version of Spring (according to docs):
public interface CrudRepository<T, ID extends Serializable>
extends Repository<T, ID> {
Optional<T> findById(ID primaryKey);
// .... other methods ...
}
So, the first thing I would change in your code is :
public Optional<User> editMyUser(int id) {
return userRepository.findById(id);
}
Make your method return Optional<User>
, maybe this will help.
Also, be careful when using user returned by that new method, e.g. here
request.setAttribute("user", userService.editMyUser(id));
With Optional
you need to use get()
to obtain the actual user instance:
userService.editMyUser(id).get()
but first, you should check if that Optional actually contains the user:
Optional<User> optionalUser = userService.editMyUser(id);
if (optionalUser.isPresent()) {
User user = optionalUser.get();
// do whatever you need
} else {
// means user is null - nothing found for ID
// act accordingly
}
There is also a good documentation that Spring provides. Could be useful.
Happy Coding :)
Upvotes: 2