<select id="getEmpByCondition" resultType="Emp">
select * from t_emp where 1=1
<if test="empName != null and empName !=''">
and emp_name = #{empName}
if>
<if test="age != null and age !=''">
and age = #{age}
if>
<if test="sex != null and sex !=''">
and sex = #{sex}
if>
<if test="email != null and email !=''">
and email = #{email}
if>
select>
若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and/or去掉
总而言之 ,该标签的功能大体就是解决sql中where和后续条件之间存在多余内容或者不多余内容
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<where>
<if test="empName != null and empName !=''">
emp_name = #{empName}
if>
<if test="age != null and age !=''">
and age = #{age}
if>
<if test="sex != null and sex !=''">
and sex = #{sex}
if>
<if test="email != null and email !=''">
and email = #{email}
if>
where>
select>
<if test="empName != null and empName !=''">
emp_name = #{empName} and
if>
<if test="age != null and age !=''">
age = #{age}
if>
select * from t_emp
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<trim prefix="where" suffixOverrides="and|or">
<if test="empName != null and empName !=''">
emp_name = #{empName} and
if>
<if test="age != null and age !=''">
age = #{age} and
if>
<if test="sex != null and sex !=''">
sex = #{sex} or
if>
<if test="email != null and email !=''">
email = #{email}
if>
trim>
select>
//测试类
@Test
public void getEmpByCondition() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
List<Emp> emps= mapper.getEmpByCondition(new Emp(null, "张三", null, null, null, null));
System.out.println(emps);
}
choose、when、otherwise
相当于if...else if..else
<select id="getEmpByChoose" resultType="Emp">
select * from t_emp
<where>
<choose>
<when test="empName != null and empName != ''">
emp_name = #{empName}
when>
<when test="age != null and age != ''">
age = #{age}
when>
<when test="sex != null and sex != ''">
sex = #{sex}
when>
<when test="email != null and email != ''">
email = #{email}
when>
<otherwise>
did = 1
otherwise>
choose>
where>
select>
,
<delete id="deleteMoreByArray">
delete from t_emp where eid in
<foreach collection="eids" item="eid" separator="," open="(" close=")">
#{eid}
foreach>
delete>
<insert id="insertMoreByList">
insert into t_emp values
<foreach collection="emps" item="emp" separator=",">
(null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.email},null)
foreach>
insert>
标签<sql id="empColumns">eid,emp_name,age,sex,emailsql>
标签
<select id="getEmpByCondition" resultType="Emp">
select <include refid="empColumns">include> from t_emp
select>