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<User> {
public NamedParameterJdbcTemplate jdbc;
private final RoleRepository<Role> roleRepository;
private final BCryptPasswordEncoder encoder;
@Override
public User create(User user) {
// check if email is unique
if(getEmailCount(user.getEmail().trim().toLowerCase()) > 0) {
throw new ApiException("Email already in use. Please use a different email and try again.");
}
// 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("userId", user.getId(), "url", 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("An error occurred. Please try again.");
}
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("email", 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";