您的位置:首页 > 其它

mybatis查询主要有三种方式实现

2016-05-18 15:11 721 查看
mybatis查询主要有三种方式实现:

方式一:<select id="selectResouceInfoByNotNullAttributes" resultMap="ExpandResultMap" parameterType="bean类名">    select * from table_name where 1=1      <if test="resourceId != null">        and resource_id = #{resourceId,jdbcType=INTEGER}      </if>      <if
test="appid != null">       and  appid = #{appid,jdbcType=TINYINT}      </if>      <if test="resourceUrl != null">       and  resource_url = #{resourceUrl,jdbcType=VARCHAR}      </if>      <if test="resourceDesc != null">       and  resource_desc = #{resourceDesc,jdbcType=VARCHAR}     
</if>  </select>

这种方式的要点在where后面的1=1,加上这个能够避免第一个if条件后面是否需要加and的选择困境。

2

方式二:<select id="selectResouceInfoByNotNullAttributes" resultMap="ExpandResultMap" parameterType="bean类名">    select * from 表名    <where>      <if test="resourceId != null">        and resource_id = #{resourceId,jdbcType=INTEGER}      </if>      <if test="appid
!= null">       and  appid = #{appid,jdbcType=TINYINT}      </if>      <if test="resourceUrl != null">       and  resource_url = #{resourceUrl,jdbcType=VARCHAR}      </if>      <if test="resourceDesc != null">       and  resource_desc = #{resourceDesc,jdbcType=VARCHAR}     
</if>    </where>  </select>

这种方式比第一种多了一个where标签,而且不需要在where后面显示的加一个1=1的字段。

3

方式三:<select id="selectResouceInfoByNotNullAttributes" resultMap="ExpandResultMap" parameterType="bean类名">    select * from 表名    <trim prefix = "where" prefixOverrides="and|or">      <if test="resourceId != null">        and resource_id = #{resourceId,jdbcType=INTEGER}     
</if>      <if test="appid != null">       and  appid = #{appid,jdbcType=TINYINT}      </if>      <if test="resourceUrl != null">       and  resource_url = #{resourceUrl,jdbcType=VARCHAR}      </if>      <if test="resourceDesc != null">       and  resource_desc
= #{resourceDesc,jdbcType=VARCHAR}      </if>    </trim>  </select>

第三种方式是最值得提倡的方式,其中的trim标签中标记该标签是以where为前缀的,即where条件的字句。后面的prefixOverrides="and|or"是说如果where标签中包含的内容开头是and或者or,那么久忽略and或者or。还有另外一个:suffixOverrides="and|or",表示where字句中是and或者or结尾则忽略and或者or的意思。

1)id必须与mapper.java里的函数名称一致2)注意sql语句的原格式,去掉if等标签后也要是一个正确的语句3)trim语句可以包含前缀和后缀,前缀用prefix表示,后缀用suffix表示,以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;正因为trim有这样的功能,所以我们也可以非常简单的利用trim来代替where元素的功能

END

注意事项

1)id必须与mapper.java里的函数名称一致

2)注意sql语句的原格式,去掉if等标签后也要是一个正确的语句

3)trim语句可以包含前缀和后缀,前缀用prefix表示,后缀用suffix表示,以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;正因为trim有这样的功能,所以我们也可以非常简单的利用trim来代替where元素的功能
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: