日期:2014-05-16  浏览次数:20629 次

mybatis使用经验之查询
[size=small][size=xx-large][size=medium][size=xx-small]今天给大家分享一下mybatis查询的使用方法,希望我的分享能够帮到有需要的人


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的选择困境。
方式二:<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的字段。
方式三:<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元素的功能

原博客地址:
http://jingyan.baidu.com/article/af9f5a2dd8143b43140a4520.html
关于怎样通过sshpass来动态获取日志文件请看下面的文章。
http://jingyan.baidu.com/article/cd4c29