分页查询

利用 limit 设置每页 offset 偏移量和每页 size 大小

select * from sys_user u
LEFT JOIN sys_user_site s ON u.user_id = s.user_id
LEFT JOIN sys_dept d ON d.dept_id = s.dept_id
LEFT JOIN sys_emailinfo e ON u.user_id = e.userid AND e.MAIN_FLAG = 'Y'
<where>
 <include refid="userCondition"/>
</where>
limit #{offset}, #{limit}
预置sql字段
<sql id="columns">
  id,title,content,original_img,is_user_edit,province_id,status,porder
</sql>

<select id="selectById" resultMap="RM_MsShortcutPanel">
 seelct
 <include refid="columns"/>
 from cms_self_panel
 where
 id = #{_parameter}
</select>
一对多级联查询

利用 mybatis 的 collection 标签,可以在每次查询文章主体同时通过 queryparaminstancelist 级联查询出关联表数据。

<resultMap id="BaseResultMap" type="com.unicom.portal.pcm.entity.ArticleEntity">
 <id column="id" jdbcType="BIGINT" property="id"/> 
 <collection property="paramList" column="id" select="queryparaminstancelist"/>
</resultMap>
<select id="queryparaminstancelist" resultMap="ParamInstanceResultMap">
 select * from `cms_article_flow_param_instance` where article_id=#{id} 
</select>
foreach 搭配 in 查询

利用 foreach 遍历 array 集合的参数,拼成 in 查询条件

<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
 #{item}
</foreach>
利用 if 标签拼装动态 where 条件
select r.*, (select d.org_name from sys_dept d where d.dept_id = r.dept_id) deptName from sys_role r
<where>
    r.wid = #{wid}
    <if test="roleName != null and roleName.trim() != ''">
    and r.`role_name` like concat('%',#{roleName},'%')
    </if>
    <if test="status != null and status.trim() != ''">
    and r.`status` = #{status}
    </if>
</where>
利用 choose 和 otherwise 组合标签拼装查询条件
<choose>
 <when test="sidx != null and sidx.trim() != ''">
 order by r.${sidx} ${order}
 </when>
 <otherwise>
 order by r.role_id asc
 </otherwise>
</choose>
隐形绑定参数:_parameter

_parameter 参数的含义当 Mapper、association、collection 指定只有一个参数时进行查询时,可以使用 _parameter,它就代表了这个参数。另外,当使用 Mapper指定方法使用 @Param 的话,会使用指定的参数值代替。

SELECT id, grp_no grpNo, province_id provinceId, status FROM tj_group_province
<where> 
 ...
 <if test="_parameter!=null">
 and grp_no = #{_parameter}
 </if>
</where>
利用 set 配合 if 标签,动态设置数据库字段更新值
<update id="updateById">
 UPDATE cms_label
 <set>
   <if test="labelGroupId != null">
     label_group_id = #{labelGroupId},
   </if>
   dept_id = #{deptId},
   <if test="recommend != null">
     is_recommend = #{recommend},
   </if>
 </set>
 WHERE label_id = #{labelId} 
</update