学习Mybatis中的动态sql

一、动态sql,比如说利用sql查询年龄为21,姓名为“jcc”的人。

<select id="queryByNameOrASqlTag" parameterType="Person" resultType="Person">
	  	select id,name,age,sex from person where
	  	<if test="name !=null and name!=''">
	  		name = #{name}
	  	</if>
	  	<if test="age !=null and age!=0">
	  		and age = #{age}
	  	</if>
	  </select>

  在select标签中,可以写上条件语句判断,name与age是否为空。

如果出现name为空的情况,sql为:select id ,name ,age,sex from person where and age = 21,那么运行测试类就会出现sql语句报错。

第一种方法可以在where后面写一句1=1,就是不论你name和age是不是空sql都会执行成功。

第二种方法:在select标签中添加where标签,该标签会自动识别删除第一个and,不会处理后面的and。

 <select id="queryByNameOrASqlTag2" parameterType="Person" resultType="Person">
	  	select id,name,age,sex from person
	  	<where>
		  	<if test="name !=null and name!=''">
		  		and name = #{name}
		  	</if>
		  	<if test="age !=null and age!=0">
		  		and age = #{age}
		  	</if>
	  	</where>
	  </select>

  二、动态sql,利用foreach标签循环找出id值为1,2,3的人。

创建实体类Id,定义private List<integer> List_id,生成set和get。

<select id="queryPersonWithId" parameterType="Id" resultType="Person">
	  	select id,name,age,sex from person
	  	<where>
		  	<if test="List_id !=null and List_id.size>0">
			  	<foreach collection="List_id" open="and id in (" close=")" item="item" separator=",">
			  		#{item}
		  		</foreach>
			  		
		  	</if>
	  	</where>
	  </select>

  在if标签语句中加入foreach标签,collection是集合,open是where和集合中间的sql语句,close是末尾的语句,集合中的每一个值item,separator是集合中的元素以逗号为间隔符。

也可以输入参数为int[]数组。

<!--  传入参数为int集合-->
      <select id="queryPersonWithId2" parameterType="int[]" resultType="Person">
          select id,name,age,sex from person
          <where>
              <if test="array!=null and array.length>0">
                  <foreach collection="array" open="and id in (" close=")" item="item" separator=",">
                      #{item}
                  </foreach>
                      
              </if>
          </where>
      </select>

如果输入参数为对象数组person[],那么parameterType="Object[]"

三、引用sql语句。

在personMapper.xml中写入标签<sql id="...."></sql>,里面写入会多次使用到sql语句。

<sql id="Intshuzu">
		<where>
		  	<if test="array!=null and array.length>0">
			  	<foreach collection="array" open="and id in (" close=")" item="item" separator=",">
			  		#{item}
		  		</foreach>
			  		
		  	</if>
	  	</where>
	</sql>

  然后在数据库操作语句中。添加标签<include refid="...."></include>即可完成引用。,如果想要引用的sql语句在别的Mapper.xml中,那么在refid后面加上具体路径即可。

posted @ 2020-11-11 22:23  Double晨  阅读(130)  评论(0编辑  收藏  举报