java.util.NoSuchElementException: No value present exception thrown when tried to check whether the emailID is registered or not in POSTGRES database

Viewed 564

I am new to Spring boot, I have tried to check with unregistered emailID whether the given email id is available or not in the Postgres database. But unfortunately got this NoSuchElementException. I have attached an exception screenshot here for your reference. Can you guys help me to come out of this problem?.

TipTopController.java

@RestController
@RequestMapping(path = "/user")
public class TipTopController {

    @Autowired
    private UserService userService;

    @PostMapping(path = "/registration")
    public ResponseEntity<UserRegistrationResponse> registration(@RequestBody UserRegistrationModel userRegistrationModel){
        UserRegistrationResponse userRegistrationResponse = userService.doUserRegistration(userRegistrationModel);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("description","User created successfully");
        return ResponseEntity.status(HttpStatus.OK)
                .headers(httpHeaders)
                .body(userRegistrationResponse);
    }

}

UserService.java

@Service
public class UserService {

    private static final Logger logger = LogManager.getLogger(UserService.class);

    @Autowired
    private UserRepository userRepository;

    @Transactional
    public UserRegistrationResponse doUserRegistration(UserRegistrationModel userRegistrationModel){
        UserRegistrationResponse userRegistrationResponse = new UserRegistrationResponse();
        try{
                logger.info("Entering into try block");
                Optional<UserInformationRepo> userInformationRepo=userRepository.findById(userRegistrationModel.getEmail());
                logger.info("Get value is "+userInformationRepo.get().getEmail());
                logger.info("Username is "+userInformationRepo.get().getFirstName()+" "+userInformationRepo.get().getLastName());
                if(userInformationRepo.isPresent()){
                    userRegistrationResponse.setStatus(false);
                    userRegistrationResponse.setMessage("This email id { "+userRegistrationModel.getEmail()+" } is taken by another user already");
                }
            else{
                    UserInformationRepo userInformationRepoSave = new UserInformationRepo();
                    userInformationRepoSave.setEmail(userRegistrationModel.getEmail());
                    userInformationRepoSave.setFirstName(userRegistrationModel.getFirstName());
                    userInformationRepoSave.setEmail(userRegistrationModel.getLastName());
                    userInformationRepoSave.setEmail(userRegistrationModel.getPassword());
                    userRepository.save(userInformationRepoSave);
                    userRegistrationResponse.setStatus(true);
                    userRegistrationResponse.setMessage("New user account created with your " + userRegistrationModel.getEmail() + " emailId");
            }
        }
        catch (Exception e){
            logger.error(e.getMessage()+"*****"+e);
            System.out.println("Exception occurred");
        }
        return userRegistrationResponse;
    }
}

UserInformationRepo.java

@Entity
@Table(name = "USER_INFORMATION")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class UserInformationRepo {
    @Id
    @Column(name = "EMAIL")
    private String email;
    @Column(name="FIRSTNAME")
    private String firstName;
    @Column(name="LASTNAME")
    private String lastName;
    @Column(name="PASSWORD")
    private String password;
}

UserRepository.java

@Repository
public interface UserRepository extends JpaRepository<UserInformationRepo, String> {
}

This is the exception I got while tried to hit the registration API from POSTMAN tool

Full StackTrace for your reference

1 Answers
  1. Are you sure that com.ajithan.tiptop.tiptopapplication.domain.UserInformationRepo is a correct fully qualified class name?

  2. Are you sure that the entity UserInformationRepo has an appropriate constructor for this:

UserInformationRepo(UI.EMAIL,UI.FIRSTNAME,UI.LASTNAME,UI.PASSWORD)
  1. You should not use a native query for this. You can use JPA query in this way:
@Transactional
@Query(value = "select new com.ajithan.tiptop.tiptopapplication.domain.UserInformationRepo(UI.email,UI.firstName,UI.lastName,UI.password) from UserInformationRepo UI where UI.email = :email")
UserInformationRepo checkUserExists(@Param("email") String email);
  1. Why you can't just use the standard method?
Optional<UserInformationRepo> findById(String id);

You can avoid to use your custom methods checkUserExists and saveNewUser and start to use the standard JpaRepository methods findById and save in this way:

@Transactional
public UserRegistrationResponse doUserRegistration(UserRegistrationModel userRegistrationModel)
{
   UserRegistrationResponse userRegistrationResponse = new UserRegistrationResponse(); // this was missed !!!
   try{
      logger.info("Entering into try block");
      Optional<UserInformationRepo> userInformationRepo = userRepository.findById(userRegistrationModel.getEmail());
      System.out.println(userInformationRepo.getEmail());
      if(userInformationRepo.isPresent()){
         userRegistrationResponse.setStatus(false);
         userRegistrationResponse.setMessage("This email id { "+userRegistrationModel.getEmail()+" } is taken by another user already");
         
      }
      else{
         UserInformationRepo userInfo = new UserInformationRepo();
         userInfo.setEmail(userRegistrationModel.getEmail());
         userInfo.setFirstName(userRegistrationModel.getFirstName())
         userInfo.setLastName(userRegistrationModel.getLastName());
         userInfo.setPassword(userRegistrationModel.getPassword());
         userRepository.save(userInfo);
         
         userRegistrationResponse.setStatus(true);
         userRegistrationResponse.setMessage("New user account created with your " + userRegistrationModel.getEmail() + " emailId");
      }
   }
   catch (Exception e){
      logger.error(e.getMessage()+"*****"+e);
      System.out.println("Exception occurred");
   }
   return userRegistrationResponse;
}
Related