修改用户信息,设置user.setLoginName(null),报错Column 'LoginName' cannot be null

来源:9-4 用户名重复校验与自定义异常

zlog

2024-02-29

登录名设置为空,修改用户信息的时候,报错:SQLIntegrityConstraintViolationException: Column ‘LoginName’ cannot be null

为啥跟老师的不一样?

public void save(UserSaveReq req) {
        User user = CopyUtil.copy(req, User.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            User userDB = selectByLoginName(req.getLoginName());
            if (ObjectUtils.isEmpty(userDB)) {
                // 新增
                user.setId(snowFlake.nextId());
                userMapper.insert(user);
            } else {
                // 用户名已存在
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            }
        } else {
            // 更新
            user.setLoginName(null);
            userMapper.updateByPrimaryKeySelective(user);
        }
    }
写回答

2回答

wzp_lucy

2024-12-22

想我这样分开写,这样就不需要再一个方法里修改了,不然后面维护的话,很麻烦

https://img1.sycdn.imooc.com/szimg/6767edbb0845b3e615890929.jpg

https://img1.sycdn.imooc.com/szimg/6767edbb08a493da15730799.jpg

https://img1.sycdn.imooc.com/szimg/6767edbb086296ea18671365.jpg


1
1
zlog
好清晰,谢谢
2025-01-05
共1条回复

zlog

提问者

2024-02-29

我知道了,应该用这个方法去更新:updateByPrimaryKeySelective,之前报错的是这个:updateByPrimaryKey

1
0

Spring Boot+Vue3前后端分离,实战wiki知识库系统

一课掌握前后端最火框架,更有职场竞争力

2566 学习 · 1679 问题

查看课程