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>