Mybatis 动态SQL语句

 mybatis核心,对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接、组装。


 if标签

    if 标签可用在许多类型的 sql 语句中,我们以查询为例。首先看一个很普通的查询:
<!-- 模糊查询 -->
	<select id="all" parameterType="String" resultType="Student">
		select * from
		student where name like CONCAT('%',#{name},'%')
	</select>

但是此时如果name或studentSex为null,此语句很可能报错或查询结果为空。此时我们使用if动态sql语句先进行判断,如果值为null或等于空字符串,我们就不进行此条件的判断,增加灵活性。

  参数为实体类Student。将实体类中所有的属性均进行判断,如果不为空则执行判断条件。


<!-- if(判断参数) - 将实体类不为空的属性作为where条件 parameterType="Student"对象哦! -->
	<!-- if + where 的条件判断 -->
	<select id="all3" parameterType="Student" resultType="Student">
		select * from student
		<!-- where 1=1 -->
		<where>
			<if test="name != null">
				and name like CONCAT('%',#{name},'%')
			</if>
			<if test="sex != null">
				and sex=#{sex}
			</if>
		</where>
	</select>


使用时比较灵活, new一个这样的实体类,我们需要限制那个条件,只需要附上相应的值就会where这个条件,相反不去赋值就可以不在where中判断。

@Test
	public void all2() throws Exception {
		// 1.会话对象
		SqlSession session = MybatisUtil.getSession(true);
		
		// 2.获得接口对象
		StudentMapper mapper = session.getMapper(StudentMapper.class);
		
		// 3.调用方法
		Student student = new Student();
//		student.setName("方");
		student.setSex("女");
		List<Student> list = mapper.all2(student);
		for (Student st : list) {
			System.out.println(st);
		}
		
		// 4.关闭会话
		session.close();
	}


if + set 的更新语句

当update语句中没有使用if标签时,如果有一个参数为null,都会导致错误。

当在update语句中使用if标签时,如果前面的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号。

	<!-- 4 if/set(判断参数) - 将实体类不为空的属性更新 -->
	<update id="update" parameterType="Student">
		update student
		<set>
			<if test="name!=null">
				name=#{name}
			</if>
			<if test="sex!=null">
				sex=#{sex}
			</if>
			<if test="birthday!=null">
				birthday=#{birthday}
			</if>
		</set>
		where id=#{id}
	</update>

@Test
	public void up() throws Exception {
		// 1.会话对象
		SqlSession session = MybatisUtil.getSession(true);

		// 2.获得接口对象
		StudentMapper mapper = session.getMapper(StudentMapper.class);

		// 3.调用方法
		Student student = new Student();
		student.setName("唐菲菲");
		//student.setSex("男");
		student.setId(4);
		 
		int count = mapper.update(student);

		// 4.关闭会话
		session.close();
	}




显示效果


 

 if + trim代替where/set标签


       trim是更灵活的去处多余关键字的标签,他可以实践where和set的效果。

trim代替where

   

	<select id="all4" parameterType="Student" resultType="Student">
		select * from student
		<!-- prefixOverrides="AND|OR" 必须是大写哦! -->
		<trim prefix="where" prefixOverrides="AND|OR">
			<if test="name != null">
				name like CONCAT('%',#{name},'%')
			</if>
			<if test="sex != null">
				and sex=#{sex}
			</if>
		</trim>
	</select>

trim代替set

<update id="update" parameterType="Student">
		update student
		<trim prefix="set" suffixOverrides=",">
			<if test="name!=null">
				name=#{name},
			</if>
			<if test="sex!=null">
				sex=#{sex},
			</if>
			<if test="birthday!=null">
				birthday=#{birthday}
			</if>
		</trim>
		where id=#{id}
	</update>


choose (when, otherwise) 分支,只执行一个条件!

  choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。
<select id="all4" parameterType="Student" resultType="Student">
		select * from student
		<!-- prefixOverrides="AND|OR" 必须是大写哦! -->
		<trim prefix="where" prefixOverrides="AND|OR">
			<choose>
				<when test="name != null">
					name like CONCAT('%',#{name},'%')
				</when>
				<when test="sex != null">
					and sex=#{sex}
				</when>
				<otherwise>
				</otherwise>
			</choose>

		</trim>
	</select>



@Test
	public void all4() throws Exception {
		// 1.会话对象
		SqlSession session = MybatisUtil.getSession(true);
		
		// 2.获得接口对象
		StudentMapper mapper = session.getMapper(StudentMapper.class);
		
		// 3.调用方法
		Student student = new Student();
//		student.setName("方");
		student.setSex("女");
		List<Student> list = mapper.all4(student);
		for (Student st : list) {
			System.out.println(st);
		}
		
		// 4.关闭会话
		session.close();
	}

显示效果:

  


foreach

     对于动态SQL 非常必须的,主是要迭代一个集合,通常是用于IN 条件。

     List 实例将使用“list”做为键,

     数组实例以“array” 做为键。

foreach元素是非常强大的,它允许你指定一个集合,声明集合项和索引变量,它们可以用在元素体内。

它也允许你指定开放和关闭的字符串,在迭代之间放置分隔符。这个元素是很智能的,它不会偶然地附加多余的分隔符。

注意:你可以传递一个List实例或者数组作为参数对象传给MyBatis。当你这么做的时候,MyBatis会自动将它包装在一个Map中,用名称在作为键。List实例将会以“list”作为键,而数组实例将会以“array”作为键。

这个部分是对关于XML配置文件和XML映射文件的而讨论的。下一部分将详细讨论Java API,所以你可以得到你已经创建的最有效的映射。


 1)参数为array

//foreach in array
	public List<Student> all6(Integer[] ids) throws Exception;

 动态 SQL 语句:
 
<!--  6 foreach(循环array参数) - 作为where中in的条件 -->  
	<select id="all6" parameterType="Student" resultType="Student">
		select * from student
		<!-- prefixOverrides="AND|OR" 必须是大写哦! -->
		<trim prefix="where" prefixOverrides="AND|OR">
		   id in 
		   <foreach collection="array" item="ids" open="(" separator="," close=")">
		     #{ids}
		   </foreach>
		</trim>
	</select>

@Test
	public void all6() throws Exception {
		// 1.会话对象
		SqlSession session = MybatisUtil.getSession(true);
		
		// 2.获得接口对象
		StudentMapper mapper = session.getMapper(StudentMapper.class);
		
		// 3.调用方法
		List<Student> list = mapper.all6(new Integer[]{2,3,5});
		
		for (Student st : list) {
			System.out.println(st);
		}
		
		// 4.关闭会话
		session.close();
	}

效果:


2)参数为list

 
//foreach in list
	public List<Student> all7(List<Integer> idList) throws Exception;

动态 SQL 语句:

<!--  7 foreach(循环array参数) - 作为where中in的条件 -->  
	<select id="all7" parameterType="Student" resultType="Student">
		select * from student
		<!-- prefixOverrides="AND|OR" 必须是大写哦! -->
		<trim prefix="where" prefixOverrides="AND|OR">
		   id in 
		   <foreach collection="list" item="idList" open="(" separator="," close=")">
		     #{idList}
		   </foreach>
		</trim>
	</select>


@Test
	public void all7() throws Exception {
		// 1.会话对象
		SqlSession session = MybatisUtil.getSession(true);

		// 2.获得接口对象
		StudentMapper mapper = session.getMapper(StudentMapper.class);

		// 3.调用方法
		List<Integer> idList = new ArrayList<Integer>();
		idList.add(5);
		idList.add(6);
		List<Student> list = mapper.all7(idList);

		for (Student st : list) {
			System.out.println(st);
		}

		// 4.关闭会话
		session.close();
	}

显示效果:







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值