mybatis学习笔记4-动态SQL

mybatis支持在mapper中配置动态sql,根据传入参数确定sql语句中的where条件。个人认为框架支持动态sql是挺好的。不过如果编程之前能预知sql使用情况的,多写几个静态sql对于系统性能还是有好处的,毕竟动态sql还是需要做一次代码解析的。

mybatis的动态sql具体的机制包括:
1. if:普通的条件判断,比较适合在一个固定条件的前提下叠加动态条件。例如:
<select id="findUser3" resultMap="usermap">
	select 
		a.id as user_id,
		a.name as user_name,
		a.sex as user_sex,
		a.age as user_age
	from T_User a where a.age=20
	<if test="name!=null">
		AND a.name=#{name}
	</if>
</select>

2. choose,when,otherwise:类似switch,满足其中一个when分支或otherwise
3. where,if:单存使用if语句在没有固定where条件的时候,容易造成最终组装出来的sql语法错误。增加where标记可以避免。例如:
<select id="findUser4" resultMap="usermap">
	select 
		a.id as user_id,
		a.name as user_name,
		a.sex as user_sex,
		a.age as user_age
	from T_User a
	<where>
		<if test="name!=null">
			a.name=#{name}
		</if>
		<if test="fname!=null">
			AND a.fname=#{fname}
		</if>
	</where>
</select>

4. foreach.特别适用于使用in条件查询的情况。一开始不知道in里面要放多少个条件,可以使用foreach来接收一个列表,动态生成一个sql。例如:
<select id="findUserByIds" resultMap="usermap">
	select 
		a.id as user_id,
		a.name as user_name,
		a.sex as user_sex,
		a.age as user_age
	from T_User a where a.id in
	<foreach collection="list" index="index" item="item"
		open="(" close=")" separator=",">
		#{item}
	</foreach>
</select>

猜你喜欢

转载自cnflat.iteye.com/blog/2106219