Mybatis动态SQL

…衆ロ難τιáo~ 提交于 2020-02-19 04:16:36
动态SQL常用的标签

1.< if >标签
2.< where >标签
3.< foreach >标签

示例一 < if >标签与< where >标签的使用

<!--我们可以把常用sql语句定义然后使用时直接调用即可-->
<sql id="default"> select * from user</sql>
<select id="findState" parameterType="cn.msg.bean.User" resultType="cn.msg.bean.User">
		<!--引用sql语句-->
        <include refid="default"></include>
        <!--以下内容为如果任意一个属性不为空或默认值,就添加相应的sql条件-->
          <where>
              <if test="name!=null">
                  and name = #{name}
              </if>
              <if test="id!=0">
                  and id = #{id}
              </if>
              <if test="money!=0.0">
                  and money = #{money}
              </if>
          </where>
    </select>

示例二 < foreach >标签的使用

<!--Ids类是我自己定义的一个javaBean里面有一个List类型的属性:list-->
<!--foreach标签就是一个字符串拼接的过程 collection属性为遍历对象  open属性为 开始的字符串
	separator属性为每遍历一次要添加的字符串 close属性为 结束的字符串 
  -->
 <select id="findByID" resultType="cn.msg.bean.User" parameterType="cn.msg.bean.Ids">
        <include refid="default"></include>
        <where>
            <if test="list!=null and list.size > 0">
                <foreach collection="list" open=" id in (" close=")" item="id" separator=",">
                  #{id}
                </foreach>
            </if>
        </where>
    </select>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!