Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Mismatch cannot convert from type Optional<User> to User

I am trying to create a website that allows the user to update, edit, delete, etc., and I have got to the part of Updating or Editing user’s information. I have tried multiple times using different ways, but I cannot seem to get past the error. I am completely oblivious to Optional<> I just don’t get it. I have read https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html, but i dont understand how it should be coded, its just not clicking. If someone could please inform on how it should be coded in my code and please explain it I would be so grateful. Maybe its because im overworked and have not slept, but i cannot seem to correct this error. This is the error i get on the page when i attempt to edit the information for a user:

There was an unexpected error (type=Internal Server Error, status=500). For input string: "id" java.lang.NumberFormatException: For input string: id

    //Repository

    public interface UserRepository extends CrudRepository<User, Integer> {
     }

here is the UserService

    //UserService

    @Service
    @Transactional
    public class UserService {

        private final UserRepository userRepository;

        public UserService(UserRepository userRepository) {
            this.userRepository=userRepository;

        }
        public void saveMyUser(User user) {
            userRepository.save(user);
        }

        public List<User> showAllUsers(){

            List<User> users = new ArrayList<User>();
            for(User user: userRepository.findAll()) {
                users.add(user);
            }

            return users;
        }

        public void deleteMyUser(int id) {
            userRepository.deleteById(id);

        }

        public User editUser (int id) {

            return userRepository.findById(id);//I also get an error here as well
        }

    }

here is the controller

    //Application Controller

    @Controller
    public class ApplicationController {

        @Autowired
        private UserService userService;

        // THIS IS WHERE I GET THE ERROR

        @RequestMapping("/edit-user")
        public String editUser(@RequestParam int id,HttpServletRequest request) {

            /* OPTIONAL<?> is this where i would implement the 
               optional what do i have to put here exactly? 
               I tried some ways I read about but its not working for me */

            request.setAttribute("user", userService.editUser(id));
            request.setAttribute("mode", "MODE_UPDATE");
            return "welcome";
        }

    }

Thank you for the help in advance Im a little frustrated with this because I have been trying to correct this error all night.

like image 437
user4138475 Avatar asked May 16 '20 03:05

user4138475


People also ask

Is it possible to return an object T instead of optional?

They have changed return type from T to Optional<T> to avoid NullPointerException. I don't see any point in replacing it to return your object T instead of Optional but if you still want to do you need to override the findById (ID id) or you can use JPARepository instead of CrudRepository and call method getOne (ID id).

Why can't I return an optional type in a Poo?

Because Optional is a wrapper and value-based class, there are some operations that can't be done against Optional object. Many times, it's just simply better to return the actual type rather than an Optional type. Generally speaking, for getters in POJOs, it's more suitable to return the actual type, not an Optional type.

What is the use of optional return type in Java?

The Optional type was introduced in Java 8. It provides a clear and explicit way to convey the message that there may not be a value, without using null. When getting an Optional return type, we're likely to check if the value is missing, leading to fewer NullPointerException s in the applications.


1 Answers

There are several ways to convert from an option to an entity. You can use the following:

Use get() method:

 public User editUser (int id) {
      return userRepository.findById(id).get();
 }

Use orElse method:

public User editUser (int id) {
    /* new User() is stab if user was not found */
    return userRepository.findById(id).orElse(new User());
}

Use orElseThrowMethod:

public User editUser (int id) {
        /* Throw exception if user was not found*/
        return userRepository.findById(id).orElseThrow(IllegalArgumentException::new));
    }

As for controller it will be like this:

        @RequestMapping("/edit-user")
        public String editUser(@RequestParam int id,HttpServletRequest request) {

            User user = userService.editUser(id);

            request.setAttribute("user", user);
            request.setAttribute("mode", "MODE_UPDATE");
            return "welcome";
        }

Also there similar question for your topic:

Spring Boot. how to Pass Optional<> to an Entity Class

like image 123
S.Dayneko Avatar answered Sep 20 '22 05:09

S.Dayneko