<selectid="getEmployeeByCond"resultType="com.lnhoo.dao.Employee"> select * from employees where <iftest="id!=null"> id=#{id} </if> <iftest="lastName!=null and lastName!=''"> and last_name like #{lastName} </if> </select>
<selectid="getEmployeeByCond"resultType="com.lnhoo.dao.Employee"> select * from employees where 1=1 <iftest="id!=null"> and id=#{id} </if> <iftest="lastName!=null and lastName!=''"> and last_name like #{lastName} </if> </select>
也可以使用where标签将所有查询条件包括在内,自动将多出来的and和or去掉,
1 2 3 4 5 6 7 8 9 10 11
<selectid="getEmployeeByCond"resultType="com.lnhoo.dao.Employee"> select * from employees <where> <iftest="id!=null"> id=#{id} </if> <iftest="lastName!=null and lastName!=''"> and last_name like #{lastName} </if> </where> </select>
使用where标签的时候,and应该放在条件语句之前,比如这里“and”就放在“last_name like #{lastName}”之前,如果放在后面拼接出的sql就不符合语法规则
3 trim自定义字符串前后缀
可以使用trim标签自定义字符串的前后缀,
1 2 3 4 5 6 7 8 9 10 11
<selectid="getEmployeeByCondTrim"resultType="com.lnhoo.dao.Employee"> select * from employees <trimprefix="where"suffixOverrides="and"> <iftest="id!=null"> id=#{id} and </if> <iftest="lastName!=null and lastName!=''"> last_name like #{lastName} and </if> </trim> </select>
<selectid="getEmployeeForEach"resultType="com.lnhoo.dao.Employee"> select * from employees where id in <foreachcollection="ids"item="eid"open="("close=")"separator=","> #{eid} </foreach> </select>
<selectid="getEmployeeByName"resultType="com.lnhoo.dao.Employee"> <bindname="_lastName"value="'%' + lastName + '%'"/> select * from employees where last_name like #{_lastName} </select>
模糊查询无法通过“#”操作符取参数值,并且如果使用“$”操作符取参数值会有sql注入的风险
bind标签可以将OGNL表达式的值绑定到1个变量中,后续可以用”#”操作符引用
9 抽取可重用的sql片段
抽取可重用的sql片段,方便后续引用,
1 2 3 4 5 6 7 8 9 10
<selectid="getEmployeeByName"resultType="com.lnhoo.dao.Employee"> <bindname="_lastName"value="'%' + lastName + '%'"/> select <includerefid="empCols"></include> from employees where last_name like #{_lastName} </select>