java.lang.NullPointerException: Cannot invoke "org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.queryForObject

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

java.lang.NullPointerException: Cannot invoke "org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.queryForObject

问题

这是我的Spring Boot v3.10 API,用于进行用户注册的POST请求,并检查电子邮件是否已经存在。但是我收到了以下错误信息:“java.lang.NullPointerException: 无法调用“org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.queryForObject(String, java.util.Map, java.lang.Class)”因为“this.jdbc”为空”。

这是创建新用户的类,但在创建用户之前,它使用getEmailCount()方法检查用户表中是否已经存在电子邮件,但这是我遇到错误的地方。

@Repository
@RequiredArgsConstructor
@Slf4j
public class UserRepositoryImplementation implements UserRepository<User> {
    public NamedParameterJdbcTemplate jdbc;
    private final RoleRepository<Role> roleRepository;
    private final BCryptPasswordEncoder encoder;

    @Override
    public User create(User user) {
        // 检查电子邮件是否唯一
        if (getEmailCount(user.getEmail().trim().toLowerCase()) > 0) {
            throw new ApiException("电子邮件已在使用中,请使用不同的电子邮件地址重试。");
        }
        // 保存新用户
        try {
            KeyHolder holder = new GeneratedKeyHolder();
            SqlParameterSource parameters = getSqlParameterSource(user);
            jdbc.update(INSERT_USER_QUERY, parameters, holder);
            user.setId(requireNonNull(holder.getKey()).longValue());

            // 向用户添加角色
            roleRepository.addRoleToUser(user.getId(), ROLE_USER.name());

            // 发送验证URL
            String verificationUrl = getVerificationUrl(UUID.randomUUID().toString(), ACCOUNT.getType());

            // 在验证表中保存URL
            jdbc.update(INSERT_VERIFICATION_QUERY, Map.of("userId", user.getId(), "url", verificationUrl));

            // 向用户发送带有验证URL的电子邮件
            //emailSerivice.sendVerificationUrl(user.getFirstName(), user.getEmail(), verificationUrl, ACCOUNT);
            user.setEnabled(false);
            user.setNotLocked(true);

            // 返回新创建的用户
            return user;
            // 如果有任何错误,抛出带有适当消息的异常
        } catch (Exception exception) {
        }
        throw new ApiException("发生错误,请重试。");
    }
}

这是处理查询以检查电子邮件是否已存在的方法:

private Integer getEmailCount(String email) {
    return jdbc.queryForObject(COUNT_USER_EMAIL_QUERY, Map.of("email", email), Integer.class);
}

如错误所述,jdbc为空。以下是COUNT_USER_EMAIL_QUERY变量的查询:

COUNT_USER_EMAIL_QUERY = "SELECT COUNT(*) FROM Users WHERE email = :email";

请确保在 UserRepositoryImplementation 类中正确初始化 NamedParameterJdbcTemplate(jdbc)以解决这个问题。

英文:
 This is my spring boot v3.10 api, a post request to register user and check if email already exist.

But i got this error: "java.lang.NullPointerException: Cannot invoke "org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.queryForObject(String, java.util.Map, java.lang.Class)" because "this.jdbc" is null"

this is the class that creates a new user but before creating it checks if an email already exist in the user table with the getEmailCount() method but this where i get the error.

@Repository
@RequiredArgsConstructor
@Slf4j
public class UserRepositoryImplementation implements UserRepository&lt;User&gt; {
public NamedParameterJdbcTemplate jdbc;
private final RoleRepository&lt;Role&gt; roleRepository;
private final BCryptPasswordEncoder encoder;
@Override
public User create(User user) {
// check if email is unique
if(getEmailCount(user.getEmail().trim().toLowerCase()) &gt; 0) {
throw new ApiException(&quot;Email already in use. Please use a different email and try again.&quot;);
}
// save new user
try{
KeyHolder holder = new GeneratedKeyHolder();
SqlParameterSource parameters = getSqlParameterSource(user);
jdbc.update(INSERT_USER_QUERY, parameters, holder);
user.setId(requireNonNull(holder.getKey()).longValue());
// add role to the user
roleRepository.addRoleToUser(user.getId(), ROLE_USER.name());
// send verification URL
String verificationUrl = getVerificationUrl(UUID.randomUUID().toString(), ACCOUNT.getType());
// save URL in verification table
jdbc.update(INSERT_VERIFICATION_QUERY, Map.of(&quot;userId&quot;, user.getId(), &quot;url&quot;, verificationUrl));
// send email to user with verification URL
//emailSerivice.sendVerificationUrl(user.getFirstName(), user.getEmail(), verificationUrl, ACCOUNT);
user.setEnabled(false);
user.setNotLocked(true);
// return the newly created user
return user;
// if any errors, throw exception with proper message
}catch (Exception exception){}
throw new ApiException(&quot;An error occurred. Please try again.&quot;);
}

This is the method that handles the query to check if the email already exist:

 private Integer getEmailCount(String email){
return jdbc.queryForObject(COUNT_USER_EMAIL_QUERY, Map.of(&quot;email&quot;, email), Integer.class);
}

As error said the jdbc is null.
This the query for the COUNT_USER_EMAIL_QUERY variable: COUNT_USER_EMAIL_QUERY = "SELECT COUNT(*) FROM Users WHERE email = :email";

答案1

得分: 0

"jdbc"没有被注入为一个Bean,也没有被初始化,因此您会得到NullPointerException。用以下代码替换:

private final NamedParameterJdbcTemplate jdbc;
英文:

"jdbc" is not injected as a bean and not initialized, therefore you are getting NullPointerException. Replace

public NamedParameterJdbcTemplate jdbc;

with

private final NamedParameterJdbcTemplate jdbc;

huangapple
  • 本文由 发表于 2023年7月24日 00:54:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76749380.html
匿名

发表评论

匿名网友

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

确定