[英]UserMapper is null in Springboot project
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:我有一个与 MySQL 交互的 UserMapper 接口,它看起来像这样:
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.在主类中,我添加了
@MapperScan()
注释,因此它应该找到映射器类的位置。
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:然后,我在 UserService 类中调用 UserMapper:
@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
.我得到的错误是
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.我还尝试在
UserMapper
界面上添加@Mapper()
,但仍然遇到相同的错误。 Does anyone know why I'm getting this error, and how to fix it?有谁知道我为什么会收到这个错误,以及如何解决它? Any help would be greatly appreciated!
任何帮助将不胜感激! Thanks!
谢谢!
Autowire Usermapper into UserService class like this:像这样将 Usermapper 自动连接到 UserService 类中:
@Autowired
private UserMapper userMapper;
Or you can use an injection like this :或者你可以使用这样的注入:
private final UserMapper userMapper;
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.