首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UserMapper在Springboot项目中为空

UserMapper在Springboot项目中为空
EN

Stack Overflow用户
提问于 2022-05-26 02:34:37
回答 2查看 143关注 0票数 0

我正在学习弹簧引导,并且正在做一个玩具项目-一个注册页面。

我有一个与UserMapper交互的MySQL接口,它看起来如下所示:

代码语言:javascript
复制
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);

在主类中,我添加了@MapperScan()注释,因此应该找到映射类的位置。

代码语言:javascript
复制
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);
    }
}

然后,我在我的UserMapper类中调用UserService:

代码语言:javascript
复制
@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;
    }
}

我得到的错误是java.lang.NullPointerException: Cannot invoke "com.example.mapper.UserMapper.insertUser(com.example.pojo.User)" because "this.userMapper" is null

我还尝试在@Mapper()接口上添加UserMapper,但仍然得到了相同的错误。有谁知道我为什么会犯这个错误,以及如何修复它?任何帮助都将不胜感激!谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-05-26 03:09:19

将用户映射器自动转到UserService类中,如下所示:

代码语言:javascript
复制
@Autowired
private UserMapper userMapper;
票数 2
EN

Stack Overflow用户

发布于 2022-05-26 03:36:44

或者你可以用这样的注射:

代码语言:javascript
复制
private final UserMapper userMapper;

public UserService(UserMapper userMapper) {
    this.userMapper = userMapper;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72386085

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档