1. 我遇到了什么问题
我在学习springboot,其中在编写CRUD时发现访问数据的函数执行下去返回值是null但是其它部分正常。
下面是我的错误代码
pojo
- public class Bot {
- @TableId(type = IdType.AUTO )
- private Integer id ;
- private Integer user_id ;
- private String name ;
- private String description ;
- private String content ;
- private Integer rating ;
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
- private Date create_time ;
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
- private Date modify_time ;
- }
复制代码 数据库列名

其中注意我是在面临访问user_id这个类时出现了返回null。当时目的是为了pojo和数据库对应。
Service
- @Service
- public class RemoveServiceImpl implements RemoveService {
- @Autowired
- BotMapper botMapper ;
- @Override
- public Map<String, String> remove(Map<String, String> data) {
- UsernamePasswordAuthenticationToken authenticationToken =
- (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication() ;
- UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal() ;
- User user = loginUser.getUser() ;
- Map<String,String> map = new HashMap<>();
- int bot_id = Integer.parseInt(data.get("bot_id")) ;
- Bot bot = botMapper.selectById(bot_id) ;
- if(bot == null) {
- map.put("error_message", "Bot不存在") ;
- return map ;
- }
- System.out.println("new BOT_ID" + bot.getId());
- System.out.println(bot.getName());
- System.out.println(bot.getUser_id());
- System.out.println(user.getId());
- if(!bot.getUser_id().equals(user.getId())) {
- map.put("error_message", "你没有权限") ;
- return map ;
- }
- botMapper.deleteById(bot_id) ;
- map.put("error_message", "success") ;
- return map ;
- }
- }
复制代码 其中各类访问数据库的函数都是idea自动填充的
问题就是当我程序进行到这个页面时,bot.getUser_id()返回值是null其它值都是正确的
后面发现pojo层的命名和数据库之间要使用驼峰命名法进行对应,关于驼峰命名法希望大家自己去查一查,因为我也不熟。但是对于数据库中的user_id列命名需要把_变为大写。
将pojo层变为- public class Bot {
- @TableId(type = IdType.AUTO )
- private Integer id ;
- private Integer userId ;
- private String name ;
- private String description ;
- private String content ;
- private Integer rating ;
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
- private Date create_time ;
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
- private Date modify_time ;
- }
复制代码 同时把service中的改为问题就解决了
我是看这位大佬的提醒懂得
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |