MyBatis 动态SQL

来源:互联网 发布:加工中心手机编程软件 编辑:程序博客网 时间:2024/06/11 14:39

if元素:

 <if test="name != null and name != ''" >     ...     </if>

choose、when、otherwise元素:

<select id="findAnalystByIds" resultType="com.bob.analyst.model.Analyst"        parameterType="com.bob.analyst.model.Analyst">        select        <include refid="Base_Column_List" />        from tbl_analyst        where 1=1         <choose>          <when test="name != null and name != ''">            and  name=#{name}          </when>          <when test="userCommentSum != null">            and  user_comment_sum = #{userCommentSum}          </when>          <otherwise>            and intro is not null          </otherwise>        </choose></select>   

trim、where、set元素

<select id="findAnalystByIds" resultType="com.bob.analyst.model.Analyst"        parameterType="com.bob.analyst.model.Analyst">        select        <include refid="Base_Column_List" />        from tbl_analyst        <where>             <if test="name != null and name != ''" >               and  name like concat('%',#{name},'%')             </if>             <if test="id != null">               and id = #{id,jdbcType=BIGINT}             </if>        </where></select>

当where元素里面的条件成立时,才会加入where这个SQL关键字组装的SQL里面,否则就不加入。
有时候需要去掉一些特殊的SQL语法,比如and、or。而是哟哦那个trim元素也可以达到预期效果:

<select id="findAnalystByIds" resultType="com.bob.analyst.model.Analyst"        parameterType="com.bob.analyst.model.Analyst">        select        <include refid="Base_Column_List" />        from tbl_analyst        <trim prefix="where" prefixOverrides="and">             <if test="name != null and name != ''" >               and  name like concat('%',#{name},'%')             </if>        </trim></select>

trim元素意味着要去掉一些特殊的字符串,prefix表示语句的前缀,prefixOverrides代表需要去掉哪种字符串。

foreach 元素
循环语句,作用就是遍历集合,它能够很好地支持数组和List、Set接口的集合。

<select id="findAnalystByIds" resultType="com.bob.analyst.model.Analyst"        parameterType="java.lang.Long">        select        <include refid="Base_Column_List" />        from tbl_analyst        where 1=1 and is_delete = 0        and id in        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">        #{item}         </foreach>    </select>

collection:传递进来的集合
item:x当前循环中的元素
index:当前元素在集合的位置下标
open和close配置的是以什么符号将这些集合元素包装起来。
separator:是各个元素的间隔符。

原创粉丝点击