Home > Software design >  UserMapper is null in Springboot project
UserMapper is null in Springboot project

Time:05-26

I'm learning spring boot and am working on a toy project - a registration page.

I have a UserMapper interface that interacts with MySQL and it looks something like this:

public interface UserMapper {

    @Insert("INSERT INTO user (email, password, salt, confirmation_code, valid_time, isValid"  
            "VALUES(#{email}, #{password}, #{salt}, #{confirmationCode}, #{validTime}, #{isValid})")
    int insertUser(User user);

In the main class, I added the @MapperScan() annotation so it's supposed to find where the mapper class is.

package com.example;

import...

@MapperScan("com.example.mapper")
@SpringBootApplication(scanBasePackages = "com.example")
public class SpringbootUserLoginApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootUserLoginApplication.class, args);
    }
}


Then, I call UserMapper in my UserService class:

@Service
public class UserService {

    private UserMapper userMapper;

    public Map<String, Object> createAccount(User user){
        // this is where the NullPointerException happens
        int result = userMapper.insertUser(user);
        Map<String, Object> resultMap = new HashMap<>();

        if (result > 0) {
            resultMap.put("code", 200);
            resultMap.put("message", "Registration successful, activate account in your email.");
        } else {
            resultMap.put("code", 400);
            resultMap.put("message", "Registration failed");
        }
        return resultMap;
    }
}

The error I got is java.lang.NullPointerException: Cannot invoke "com.example.mapper.UserMapper.insertUser(com.example.pojo.User)" because "this.userMapper" is null.

I also tried adding @Mapper() on the UserMapper interface and still got the same error. Does anyone know why I'm getting this error, and how to fix it? Any help would be greatly appreciated! Thanks!

CodePudding user response:

Autowire Usermapper into UserService class like this:

@Autowired
private UserMapper userMapper;

CodePudding user response:

Or you can use an injection like this :

private final UserMapper userMapper;

public UserService(UserMapper userMapper) {
    this.userMapper = userMapper;
}
  • Related