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

huangapple go评论74阅读模式
英文:

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

问题

以下是翻译好的部分:

我对Spring Boot还不太了解,我尝试检查未注册的emailID,以确定在Postgres数据库中是否存在给定的email id。但不幸的是,出现了NoSuchElementException异常。我已经在这里附上了异常截图供您参考。您能帮我解决这个问题吗?

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", "用户创建成功");
        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("进入try块");
                Optional<UserInformationRepo> userInformationRepo=userRepository.findById(userRegistrationModel.getEmail());
                logger.info("获取的值为 "+userInformationRepo.get().getEmail());
                logger.info("用户名为 "+userInformationRepo.get().getFirstName()+" "+userInformationRepo.get().getLastName());
                if(userInformationRepo.isPresent()){
                    userRegistrationResponse.setStatus(false);
                    userRegistrationResponse.setMessage("此email id { "+userRegistrationModel.getEmail()+" } 已被其他用户使用");
                }
                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("使用您的 "+ userRegistrationModel.getEmail() + " 邮箱成功创建新用户账户");
            }
        }
        catch (Exception e){
            logger.error(e.getMessage()+"*****"+e);
            System.out.println("发生异常");
        }
        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> {
}

这是我在尝试使用POSTMAN工具访问注册API时遇到的异常。

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

英文:

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 = &quot;/user&quot;)
public class TipTopController {
@Autowired
private UserService userService;
@PostMapping(path = &quot;/registration&quot;)
public ResponseEntity&lt;UserRegistrationResponse&gt; registration(@RequestBody UserRegistrationModel userRegistrationModel){
UserRegistrationResponse userRegistrationResponse = userService.doUserRegistration(userRegistrationModel);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(&quot;description&quot;,&quot;User created successfully&quot;);
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(&quot;Entering into try block&quot;);
Optional&lt;UserInformationRepo&gt; userInformationRepo=userRepository.findById(userRegistrationModel.getEmail());
logger.info(&quot;Get value is &quot;+userInformationRepo.get().getEmail());
logger.info(&quot;Username is &quot;+userInformationRepo.get().getFirstName()+&quot; &quot;+userInformationRepo.get().getLastName());
if(userInformationRepo.isPresent()){
userRegistrationResponse.setStatus(false);
userRegistrationResponse.setMessage(&quot;This email id { &quot;+userRegistrationModel.getEmail()+&quot; } is taken by another user already&quot;);
}
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(&quot;New user account created with your &quot; + userRegistrationModel.getEmail() + &quot; emailId&quot;);
}
}
catch (Exception e){
logger.error(e.getMessage()+&quot;*****&quot;+e);
System.out.println(&quot;Exception occurred&quot;);
}
return userRegistrationResponse;
}
}

UserInformationRepo.java

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

UserRepository.java

@Repository
public interface UserRepository extends JpaRepository&lt;UserInformationRepo, String&gt; {
}

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

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

答案1

得分: 0

  1. 你确定 com.ajithan.tiptop.tiptopapplication.domain.UserInformationRepo 是一个正确的完全限定类名 吗?

  2. 你确定实体 UserInformationRepo 有适用于以下情况的构造函数:

UserInformationRepo(UI.EMAIL, UI.FIRSTNAME, UI.LASTNAME, UI.PASSWORD)
  1. 你不应该使用原生查询来做这个。你可以使用以下方式的 JPA 查询:
@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. 为什么你不能只是使用标准的方法呢?
Optional<UserInformationRepo> findById(String id);

你可以避免使用你的自定义方法 checkUserExistssaveNewUser,并开始使用标准的 JpaRepository 方法 findByIdsave,像这样:

@Transactional
public UserRegistrationResponse doUserRegistration(UserRegistrationModel userRegistrationModel) {
   UserRegistrationResponse userRegistrationResponse = new UserRegistrationResponse(); // 这里之前漏掉了!!!
   try {
      logger.info("进入 try 块");
      Optional<UserInformationRepo> userInformationRepo = userRepository.findById(userRegistrationModel.getEmail());
      System.out.println(userInformationRepo.getEmail());
      if (userInformationRepo.isPresent()) {
         userRegistrationResponse.setStatus(false);
         userRegistrationResponse.setMessage("这个邮箱地址 { " + userRegistrationModel.getEmail() + " } 已被其他用户占用");
      } 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("使用你的 " + userRegistrationModel.getEmail() + " 邮箱创建了新用户账户");
      }
   } catch (Exception e) {
      logger.error(e.getMessage() + "*****" + e);
      System.out.println("发生异常");
   }
   return userRegistrationResponse;
}
英文:
  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 = &quot;select new com.ajithan.tiptop.tiptopapplication.domain.UserInformationRepo(UI.email,UI.firstName,UI.lastName,UI.password) from UserInformationRepo UI where UI.email = :email&quot;)
UserInformationRepo checkUserExists(@Param(&quot;email&quot;) String email);
  1. Why you can't just use the standard method?
Optional&lt;UserInformationRepo&gt; 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(&quot;Entering into try block&quot;);
      Optional&lt;UserInformationRepo&gt; userInformationRepo = userRepository.findById(userRegistrationModel.getEmail());
      System.out.println(userInformationRepo.getEmail());
      if(userInformationRepo.isPresent()){
         userRegistrationResponse.setStatus(false);
         userRegistrationResponse.setMessage(&quot;This email id { &quot;+userRegistrationModel.getEmail()+&quot; } is taken by another user already&quot;);
         
      }
      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(&quot;New user account created with your &quot; + userRegistrationModel.getEmail() + &quot; emailId&quot;);
      }
   }
   catch (Exception e){
      logger.error(e.getMessage()+&quot;*****&quot;+e);
      System.out.println(&quot;Exception occurred&quot;);
   }
   return userRegistrationResponse;
}

huangapple
  • 本文由 发表于 2020年8月24日 21:01:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63561585.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定