开发人员通常根据需求手动拼接 SQL 语句,这是一个极其麻烦的工作,而 MyBatis 提供了对 SQL 语句动态组装的功能,恰能解决这一问题。
MyBatis 的动态 SQL 元素与 JSTL 或 XML 文本处理器相似,常用
if
动态 SQL 通常要做的事情是有条件地包含 where 子句的一部分,所以在 MyBatis 中
示例:
<!--使用 if 元素根据条件动态查询用户信息--><select id="selectUserByIf" resultType="com.po.MyUser" parameterType="com.po.MyUser">select * from user where 1=1<if test="uname!=null and uname!=''">and uname like concat('%',#{uname},'%')</if ><if test="usex !=null and usex !=''">and usex=#{usex}</if ></select>
choose、when、otherwise
有些时候不想用到所有的条件语句,而只想从中择取一二,针对这种情况,MyBatis 提供了
示例:
<!--使用choose、when、otherwise元素根据条件动态查询用户信息--><select id="selectUserByChoose" resultType="com.po.MyUser" parameterType= "com.po.MyUser">select * from user where 1=1<choose><when test="uname!=null and uname!=''">and uname like concat('%',#{uname},'%')</when><when test="usex!=null and usex!=''">and usex=#{usex}</when><otherwise>and uid > 10</otherwise></choose></select>
trim、where、set
元素
可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是 prefixOverrides 和 suffixOverrides。正因为
示例
<!--使用trim元素根据条件动态查询用户信息--><select id="selectUserByTrim" resultType="com.po.MyUser"parameterType="com.po.MyUser">select * from user<trim prefix="where" prefixOverrides = "and | or"><if test="uname!=null and uname!=''">and uname like concat('%',#{uname},'%')</if><if test="usex!=null and usex!=''">and usex=#{usex}</if></trim></select>
元素
当然如果是以 or 开头的,MyBatis 也会把它忽略;此外,在
示例
<!--使用where元素根据条件动态查询用户信息--><select id="selectUserByWhere" resultType="com.po.MyUser" parameterType="com.po.MyUser">select * from user<where><if test="uname != null and uname ! = ''">and uname like concat('%',#{uname},'%')</if><if test="usex != null and usex != '' ">and usex=#{usex}</if ></where></select>
元素
在动态 update 语句中可以使用
<!--使用set元素动态修改一个用户--><update id="updateUserBySet" parameterType="com.po.MyUser">update user<set><if test="uname!=null">uname=#{uname}</if><if test="usex!=null">usex=#{usex}</if></set>where uid=#{uid}</update>
foreach
- item 表示集合中每一个元素进行迭代时的别名。
- index 指定一个名字,用于表示在迭代过程中每次迭代到的位置。
- open 表示该语句以什么开始。
- separator 表示在每次进行迭代之间以什么符号作为分隔符。
- close 表示以什么结束。
在使用
- 如果传入的是单参数且参数类型是一个 List,collection 属性值为 list。
- 如果传入的是单参数且参数类型是一个 array 数组,collection 的属性值为 array。
- 如果传入的参数是多个,需要把它们封装成一个 Map,当然单参数也可以封装成 Map。Map 的 key 是参数名,collection 属性值是传入的 List 或 array 对象在自己封装的 Map 中的 key。
示例
<!--使用foreach元素查询用户信息--><select id="selectUserByForeach" resultType="com.po.MyUser" parameterType="List">select * from user where uid in<· item="item" index="index" collection="list"open="(" separator="," close=")"># {item}</foreach></select>
bind
在进行模糊查询时,如果使用“${}”拼接字符串,则无法防止 SQL 注入问题。如果使用字符串拼接函数或连接符号,但不同数据库的拼接函数或连接符号不同。
例如 MySQL 的 concat 函数、Oracle 的连接符号“||”,这样 SQL 映射文件就需要根据不同的数据库提供不同的实现,显然比较麻烦,且不利于代码的移植。幸运的是,MyBatis 提供了
示例
<!--使用bind元素进行模糊查询--><select id="selectUserByBind" resultType="com.po.MyUser" parameterType= "com.po.MyUser"><!-- bind 中的 uname 是 com.po.MyUser 的属性名--><bind name="paran_uname" value="'%' + uname + '%'"/>select * from user where uname like #{paran_uname}</select>
