Springboot编写CRUD时访问对应数据函数返回null的问题及解决方法
作者:Fúsi
我在学习springboot,其中在编写CRUD时发现访问数据的函数执行下去返回值是null但是其它部分正常,这篇文章主要介绍了Springboot在编写CRUD时,访问对应数据函数返回null,需要的朋友可以参考下
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其它值都是正确的
2. 我是怎么做得
后面发现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中的
bot.getUser_id()
改为
bot.getUserId()
问题就解决了
到此这篇关于Springboot在编写CRUD时,访问对应数据函数返回null的文章就介绍到这了,更多相关Springboot编写CRUD返回null内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
