Mybatisz之SQL片段(21)

一、需求

将动态SQL判断代码块抽取出来,组成一个SQL片段。其它的statement中就可以引用SQL片段。

二、定义SQL片段

	<!-- 定义SQL片段
	id:sql片段的唯一标识
	
	经验:是基於单表来定义SQL片段,这样这个SQL片段的可重用性才高
	在SQL片段中不要包括where
	 -->
	<sql id="query_user_where">
		<if test="userCustom!=null">
			<if test="userCustom.sex!=null and userCustom.sex!=''">
				and user.sex = #{userCustom.sex}
			</if>
			<if test="userCustom.username!=null and userCustom.username!=''">
				and user.username like '%${userCustom.username}%'
			</if>
		</if>
	</sql>

三、使用SQL片段

	<!-- 用户信息综合查询
	#{userCustom.sex}:取出pojo包装对象中性别值
	${userCustom.username}:取出pojo包装对象中用户名称
	 -->
	<select id="findUserList" parameterType="UserQueryVo" 
		resultType="UserCustom">
		select * from user 
		<!-- 
		where可以自动去掉条件中的第一个and 
		-->
		<where>
			<!-- 引用SQL片段的id,如果refid指定的id不在本mapper文件中,
			需要前边加namespace,include标签必须写成单标签或写在一行上,
			否则会报错 -->
			<include refid="query_user_where"></include>
			<!-- 在这里还要引用其他的SQL片段 -->
		</where>
		
	</select>

四、测试

运行测试中的对应方法进行测试。

	/**
	 * 测试用户信息的综合查询
	 * @throws Exception
	 */
	@Test
	public void testFindUserList() throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//创建UserMapper对象,mybatis自动生成mapper代理对象
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//组装查询条件
//		UserCustom userCustom = new UserCustom();
//		userCustom.setSex("1");
//		userCustom.setUsername("张");
		//创建包装对象,设置查询条件
		UserQueryVo userQueryVo = new UserQueryVo();
		userQueryVo.setUserCustom(null);
		
		//调用userMapper方法
		List<UserCustom> users = userMapper.findUserList(userQueryVo);
		System.out.println(users);
	}







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章