MyBatis案例七:动态sql:if、trim、where
- 接口方法:
public List<Dept> getForExample(Dept dept);
- mapper:
<select id="getForExample" resultType="com.yy.domain.Dept">
select * from dept
where 1 = 1
<if test="deptno != null">
and deptno = #{deptno}
</if>
<if test="dname != null">
and dname = #{dname}
</if>
<if test="loc != null">
and loc = #{loc}
</if>
</select>
- 测试类:
@Test
public void testGetForExample() throws IOException {
deptMapper = session.getMapper(DeptMapper.class);
Dept dept = new Dept(null, "hr", "tt");
List<Dept> list = deptMapper.getForExample(dept);
System.out.println(list);
}
- mapper改进:trim
<select id="getForExample" resultType="com.yy.domain.Dept">
select * from dept
<trim prefix="where" prefixOverrides="and ">
<if test="deptno != null">
and deptno = #{deptno}
</if>
<if test="dname != null">
and dname = #{dname}
</if>
<if test="loc != null">
and loc = #{loc}
</if>
</trim>
</select>
- mapper改进:where
<select id="getForExample" resultType="com.yy.domain.Dept">
select * from dept
<where>
<if test="deptno != null">
and deptno = #{deptno}
</if>
<if test="dname != null">
and dname = #{dname}
</if>
<if test="loc != null">
and loc = #{loc}
</if>
</where>
</select>