首页 > mybatis 是不是对单表查询不方便啊?

mybatis 是不是对单表查询不方便啊?

1.初用mybatis, 以前用过hibernate, 实现一个通用的dao比较容易.
但是mybatis如何实现呢?
2.如果只修改我更改过的字段呢?
比如User(String name, String password, int age, int sex)
UPDATE user SET name = (#{name}), password = ({#password}), age = ({#age}), sex = ({#sex}) WHERE id = ({#id})
如果我只需要改一个age. 那么岂不是连其他的也要赋值一遍?


自动生成的代码中应该有updateBySelective方法吧。。

对传递参数加入,if 判断


使用mybatis的动态sql啊,你知道要修改哪个字段,在mapper文件中使用if标签判断下就好


两种方案:
1、可以单独写个语句修改age。
2、可以在一个update语句里判断该字段是否需要修改,比如:
<!-- 更新 -->

<update id="update" parameterType="User">
    <set>
        <if test="name != null"> name=#{name},</if>
        <if test="password != null"> password=#{password},</if>
        <if test="age != null"> age=#{age},</if>
    </set>
    WHERE id=#{id}
</update>

这样你传入的User对象如果age不空就修改age


不必。需要改什么指的直接赋值给实体类。然后传给DAO即可。
接口我这就不写了,直接给实现类。

BaseService中有

  @Transactional
  public <T extends IdEntity> boolean save(BaseDao<T> baseDao, T entity) {
    if (entity instanceof BaseEntity) {
      ((BaseEntity) entity).setDefaultBizValue();
    }
    if (entity.getId() == null) {
      return baseDao.insert(entity) > 0;
    } else {
      return baseDao.updateById(entity) > 0;
    }
  }

xml中做如下定义:

    
        <sql id="BaseUpdateSet">
        <set>
            <include refid="COMMON.BASE_UPDATE_SET"/>
            <if test="memberType != null">
                member_type = #{memberType},
            </if>
            <if test="applySn != null">
                apply_sn = #{applySn},
            </if>
            <if test="contact != null">
                contact = #{contact},
            </if>
            <if test="mobile != null">
                mobile = #{mobile},
            </if>
            <if test="serviceDetail != null">
                service_detail = #{serviceDetail},
            </if>
            <if test="mainBusinessBrand != null">
                main_business_brand = #{mainBusinessBrand},
            </if>
            <if test="remark != null">
                remark = #{remark},
            </if>
            <if test="storeId != null">
                store_id = #{storeId},
            </if>
            <if test="storeId != null">
                contract_type = #{contractType},
            </if>
            <if test="storeName != null">
                store_name = #{storeName},
            </if>
            <if test="signStatus != null">
                sign_status = #{signStatus}
            </if>
        </set>
    </sql>

    <update id="updateById">
        update contract
        <include refid="BaseUpdateSet"/>
        where id = #{id}
    </update>
【热门文章】
【热门文章】