首页 > 其他 > 详细

后台操作日志,插入数据获取的该数据主键ID为null

时间:2018-07-15 18:17:07      阅读:162      评论:0      收藏:0      [点我收藏+]

技术分享图片

 代码如下:

@Override
public void saveTopicResource(TopicResourceModel model, Integer userId) {
   TopicResource topicResource = new TopicResource();
   BeanUtils.copyProperties(model, topicResource);
   int result=0;
   if (model.getResId() == null) {
      topicResource.setCreateUser(userId);
      result = topicResourceMapper.insertSelective(topicResource);
      model.setResId(topicResource.getResId());
      if(result!=0){
         logService.log("新增", SystemObject.TopicResource.getValue(), "新增的热门主题ID为:"
               + model.getResId() + ",标题:" + model.getTopicName());
      }
   } else {
      topicResource.setUpdateUser(userId);
      topicResource.setGmtUpdate(new Date());
      result = topicResourceMapper.updateByPrimaryKeySelective(topicResource);
      if(result !=0){
         logService.log("更新", SystemObject.TopicResource.getValue(), "更新后的热门主题ID为:"
               + topicResource.getResId());
      }
   }
}
自己仔仔细细分析了一下插入数据逻辑,没啥问题啊,就是获取插入数据主键为null,然后查阅了一些资料
解决如下:首先需要把主键set进去,然后找到插入语句的SQL,添加两个属性
<insert id="insertSelective" parameterType="com.diyfintech.pojo.TopicResource" useGeneratedKeys="true" keyProperty="resId">

  解释一下啊: 

useGeneratedKeys:默认值是false

设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。MySQL和SQLServer执行auto-generated key field,
因此当数据库设置好自增长主键后,可通过JDBC的getGeneratedKeys方法获取。但像Oralce等不支持auto-generated key field的数据库就不能用这种方法获取主键了

后台操作日志,插入数据获取的该数据主键ID为null

原文:https://www.cnblogs.com/zlw-xf/p/9314244.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!