zoukankan      html  css  js  c++  java
  • 后台操作日志,插入数据获取的该数据主键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的数据库就不能用这种方法获取主键了
  • 相关阅读:
    Python网络爬虫第三弹《爬取get请求的页面数据》
    18.增量式爬虫
    17.基于scrapy-redis两种形式的分布式爬虫
    关于进程内存磁盘的一些命令
    linux其他命令
    ls -用于显示指定工作目录下之内容(列出目前工作目录所含之文件及子目录)
    mkdir和touch
    ls -列出当前目录下所有的文件或者目录
    cat -用于连接文件并打印到标准输出设备上
    rm -移动文件
  • 原文地址:https://www.cnblogs.com/zlw-xf/p/9314244.html
Copyright © 2011-2022 走看看