美文网首页
mybatisCodeHelperPro自动生成代码的全量和选择

mybatisCodeHelperPro自动生成代码的全量和选择

作者: dwwl | 来源:发表于2019-06-15 16:12 被阅读0次

    在idea中使用mybatisCodeHelperPro插件根据表自动生成实体类,mapper类,*mapper.xml时,dao中生成的新增,更新方法时,会生成insert() insertSelective(),updateByPrimaryKey() updateByPrimaryKeySelective(),带有selective的方法会对每个字段进行null的判断,在现在看来,至少是现在,最好是使用带有Selective的方法,

    举个例子:当表中有字段定义如下时,

    gmt_modified datetime default CURRENT_TIMESTAMP null on update CURRENT_TIMESTAMP comment '修改的时间',
    

    用insert()方法但没未给gmt_modified字段赋值时,传入的字段对应参数为null,但是用带有Selective的方法时,该字段会更新值(指的是更新默认值等)。

    还有这种情况:

    数据库表设计如下:

    create table person
    (
        name  varchar(20) default 'huangSir' null,
        info  varchar(80)                    null,
        hobby varchar(30) default 'asd'      not null,
        age   int                            null
    );
    

    下面的会报错:### Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException: Column 'hobby' cannot be null

            Person person = new Person();
            person.setName("p1");
            int insertNum = personMapper.insert(person);
            System.out.println(insertNum);
    

    用insertSelective()方法即可,即数据库中有default xxx not null 字段时,insert该字段 传null不行

      <insert id="insertSelective" parameterType="com.mpt.starterlearn.po.Person">
        <!--@mbg.generated-->
        insert into person
        <trim prefix="(" suffix=")" suffixOverrides=",">
          <if test="name != null">
            `name`,
          </if>
          <if test="info != null">
            info,
          </if>
          <if test="hobby != null">
            hobby,
          </if>
          <if test="age != null">
            age,
          </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
          <if test="name != null">
            #{name,jdbcType=VARCHAR},
          </if>
          <if test="info != null">
            #{info,jdbcType=VARCHAR},
          </if>
          <if test="hobby != null">
            #{hobby,jdbcType=VARCHAR},
          </if>
          <if test="age != null">
            #{age,jdbcType=INTEGER},
          </if>
        </trim>
      </insert>
    

    相关文章

      网友评论

          本文标题:mybatisCodeHelperPro自动生成代码的全量和选择

          本文链接:https://www.haomeiwen.com/subject/msbbfctx.html