myBatis中实用技巧

2023-05-07,,

技巧一:

把查询的字段,查询的条件单独写在一起,使用 <sql></sql>标签定义,使用<include></include>标签引用

<!-- 查询的字段 -->

<sql id="Base_Column_List" >

    id, name

</sql>

 

<!-- 查询的条件 -->

<sql id="QUERY">

  <where>

    <if test="id != null">

       AND id = #{id,jdbcType=INTEGER}

    </if>

    <if test="name != null">

       AND name= #{name,jdbcType=VARCHAR}

    </if>

  </where>

</sql>

 

<!-- 查询语句 -->

<select id="selectByCondition" resultMap="baseResultMap">

   select 

   

   <!-- 引入查询的字段 -->

   <include refid="Base_Column_List" />

   

   from student

 

   <!-- 引入查询的条件 -->

   <include refid="QUERY"></include>

</select>

 

技巧二:

大于小于号转义

<!-- 第一种方式:使用转义字符 -->

<if test="createTime != null">

 

  <!--   &gt; -> 大于号(>)   -->

  create_time &gt;= #{createTime ,jdbcType=DATE}

 

</if>

 

<if test="updateTime != null">

 

  <!--   &lt; -> 小于号(<)   -->

  update_time &lt;= #{updateTime ,jdbcType=DATE}

 

</if>

 

 

<!-- 第二种:xml格式 -->

<if test="createTime != null">

 

  <![CDATA[

      create_time >= #{createTime ,jdbcType=DATE}

  ]]>

 

</if>

 

<if test="updateTime != null">

 

  <![CDATA[

      update_time <= #{updateTime ,jdbcType=DATE}

  ]]>

 

</if>

 

技巧三:

插入时返回自增的主键id

<!-- myBatis中关键点就是在 insert 标签内添加 useGeneratedKeys 和 keyProperty属性 -->

 

<!-- useGeneratedKeys:如果插入的表以自增列为主键,则允许 JDBC 支持自动生成主键,并可将自动生成的主键返回 -->

 

<!-- keyProperty:对应的主键的对象 -->

 

<insert id="insertSelective" parameterType="com.test.student" useGeneratedKeys="true" keyProperty="id">

    <!-- 这里写插入 sql -->

</insert>

 

 

<!-- java代码中关键点就是,返回的自增主键不是调用的 insertSelective 方法返回结果 -->

 

<!-- 返回结果为影响行数,正确的获取方式是在入参的 student 对象中,使用 getId() 方法得到 -->

 

<!-- 这只是举例,具体的对象和对象中的id属性的getter方法不一样 -->

 

技巧四:

在插入前/插入后查询获取某个字段的值,并且使用在紧接着的第二条 sql 中

<!-- 场景描述:一个置顶功能,设置置顶的时候需要得到最大的置顶数,加一后设置为本次置顶数 -->

 

 

<!-- 在显示置顶的时候是按照倒序排列,越往后点击了置顶的数据显示的越前面 -->

 

<!-- 设置置顶 -->

<update id="updateTop">

    

    <!-- 更新前查询出最大的置顶数,并且加一后返回出来 -->

    <!-- 注: -->

    <!--    1. 更新前/更新后:BEFORE/AFTER -->

    <!--    2. 这里是在有很多数据后添加的排序字段,添加排序字段后,老数据那一列都是null -->

    <!--       则在此处使用了 COALESCE 函数做了一个小处理,如果为null就取值0 -->

 

<selectKey keyProperty="top_sort" order="BEFORE" resultType="java.lang.Integer">

select COALESCE(max(top_sort),0) + 1 from table

</selectKey>

    <!-- 设置置顶主 sql -->

    <!-- 注: -->

    <!--    1. 下面 sql 中的 #{top_sort} 是取的上面 sql中的结果 -->

 

update table

top_sort = #{top_sort} 

<if test="update_time!=null">

,update_time=#{update_time}

</if>

<if test="update_user!=null">

,update_user=#{update_user}

</if>

where id = #{id}

</update>

 

《myBatis中实用技巧.doc》

下载本文的Word格式文档,以方便收藏与打印。