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


     代码如下:

    @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的数据库就不能用这种方法获取主键了
  • 相关阅读:
    让我们来学学css3 media queries的使用吧
    Emmet(zen coding)文档(一)[译文]
    给自己不同网站的密码加密
    Photoshop图层混合模式原理(公式)
    3dsmax设置贴图路径为相对目录
    ImageMagick
    FireBreak框架: 用C++打造多浏览器支持的插件
    粒子滤波算法
    页端3d技术
    RANSAC算法
  • 原文地址:https://www.cnblogs.com/zlw-xf/p/9314244.html
Copyright © 2020-2023  润新知