// EmployeeMapper.xml映射文件中的SQL实现 <!--SQL语句字段起别名或者开启MyBatis驼峰命名配置--> <selectid="getAllEmployeesOld"resultType="Employee"> <!--select eid as eid, emp_name as empName, emp_age as empAge, emp_sex as empSex, emp_email as empEmail from t_emp--> select * from t_emp; </select>
<selectid="getEmpAndDept"resultMap="empAndDeptResultMap2"> select * from t_emp left join t_dept on t_emp.did = t_dept.did where t_emp.eid = #{eid} </select>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC"-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mappernamespace="com.huling.mapper.DynamicSQLMapper"> <!--SQL片段,方便复用--> <sqlid="empColumns">eid,emp_name,emp_age,emp_sex,emp_email,did</sql> <!--使用动态SQL最常见情景是根据条件包含where子句的一部分--> <selectid="getEmployeeByConditionOld1"resultType="Employee"> select <includerefid="empColumns"/> from t_emp where 1=1 <iftest="empName != null and empName != ''"> and emp_name = #{empName} </if> <iftest="empAge != null"> and emp_age = #{empAge} </if> <iftest="empSex != null and empSex != ''"> and emp_sex = #{empSex} </if> <iftest="empEmail != null and empEmail != ''"> and emp_email = #{empEmail} </if> </select>
<!--where元素只会在子元素返回任何内容的情况下才插入“WHERE”子句。而且,若子句的开头为“AND”或“OR”,where元素也会将它们去除--> <selectid="getEmployeeByConditionOld2"resultType="Employee"> select <includerefid="empColumns"/> from t_emp <where> <iftest="empName != null and empName != ''"> emp_name = #{empName} </if> <iftest="empAge != null"> and emp_age = #{empAge} </if> <iftest="empSex != null and empSex != ''"> and emp_sex = #{empSex} </if> <iftest="empEmail != null and empEmail != ''"> and emp_email = #{empEmail} </if> </where> </select>
<!--自定义trim元素来定制where元素--> <selectid="getEmployeeByCondition"resultType="Employee"> select <includerefid="empColumns"/> from t_emp <trimprefix="where"prefixOverrides="and|or"> <iftest="empName != null and empName != ''"> emp_name = #{empName} </if> <iftest="empAge != null"> and emp_age = #{empAge} </if> <iftest="empSex != null and empSex != ''"> and emp_sex = #{empSex} </if> <iftest="empEmail != null and empEmail != ''"> and emp_email = #{empEmail} </if> </trim> </select>
<!--foreach元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!--> <deleteid="deleteMoreByArray1"> delete from t_emp where eid in <foreachcollection="eids"item="eid"separator=","open="("close=")"> #{eid} </foreach> </delete>
<deleteid="deleteMoreByArray"> delete from t_emp where <foreachcollection="eids"item="eid"separator="or"> eid = #{eid} </foreach> </delete> <!--你可以将任何可迭代对象(如List、Set等)、Map对象或者数组对象作为集合参数传递给foreach。当使用可迭代对象或者数组时,index是当前迭代的序号,item的值是本次迭代获取到的元素。当使用Map对象(或者Map.Entry对象的集合)时,index是键,item是值。--> <insertid="insertMoreByList"> insert into t_emp values <foreachcollection="employees"item="employee"separator=","> (null,#{employee.empName},#{employee.empAge},#{employee.empSex},#{employee.empEmail},null) </foreach> </insert> </mapper>