MyBatis案例七:动态sql:if、trim、where

MyBatis案例七:动态sql:if、trim、where

  1. 接口方法:
public List<Dept> getForExample(Dept dept);
  1. 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>
  1. 测试类:
	@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);
	}
  1. 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>
  1. 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>

猜你喜欢

转载自blog.csdn.net/pcbhyy/article/details/83715517