mybatis优化写法

mapper.xml 简化技巧
insert 可复用

<sql id="setField">
    <set>
        <if test="taskVersionId != null">task_version_id = #{taskVersionId},</if>
        <if test="uid != null">uid = #{uid},</if>
        <if test="userName != null">user_name = #{userName},</if>
        <if test="greyDate != null">grey_date = #{greyDate},</if>
    </set>
</sql>
 
<insert id="insert" parameterType="com.**.**.app.grey.core.bean.GreyRecordDO">
    insert into h_grey_record
    <include refid="setField"/>
</insert>

update复用

<sql id="setUpdateField">
    <set>
        <if test="pushDevice.appId != null">app_id = #{pushDevice.appId},</if>
        <if test="pushDevice.deviceId != null">device_id = #{pushDevice.deviceId},</if>
        <if test="pushDevice.registrationId != null">registration_id = #{pushDevice.registrationId},</if>
        <if test="pushDevice.os != null">os = #{pushDevice.os},</if>
        <if test="pushDevice.osVersion != null">os_version = #{pushDevice.osVersion},</if>
        <if test="pushDevice.appVersion != null">app_version = #{pushDevice.appVersion},</if>
        <if test="pushDevice.mobileBrands != null">mobile_brand = #{pushDevice.mobileBrands},</if>
        <if test="pushDevice.mobileModel != null">mobile_model = #{pushDevice.mobileModel},</if>
        <if test="pushDevice.pushSwitchStatus != null">push_switch_status = #{pushDevice.pushSwitchStatus},</if>
        <if test="pushDevice.regIdType != null">reg_id_type = #{pushDevice.regIdType},</if>
        <if test="pushDevice.bundleId != null">bundle_id = #{pushDevice.bundleId},</if>
    </set>
</sql>

query复用

<sql id="query_user_where">
    <where>
        <if test="id!=null and id!=''"and id=#{id} </if>
        <if test="username!=null and username!=''"and username like '%${username}%' </if>
    </where>
</sql>
 
//使用include引用sql片段
<select id="findUserList" parameterType="user" resultType="user">
    select from user 
    <include refid="query_user_where"/>
</select>
posted @ 2022-01-19 10:23  隔壁w王叔叔  阅读(69)  评论(0编辑  收藏  举报