动态sql

需求1:在综合查询时,查询条件由用户输入,用户名可为空等
需求2:综合查询,根据用户ID集合进行查询

if标签:可以对输入参数进行判断

where标签:默认去掉后面第一个and,如果没有参数,则把自己干掉

sql片段

foreach标签:可以循环的传入参数值


1映射文件

<sql id="whereclause">
	<if test="user != null">
		<if test="user.username != null and user.username !=  '' ">
		 and username like '%${user.username}%'
		</if>
		<if test="user.sex != null and user.sex != '' ">
		and sex = #{user.sex}
		</if>
	</if>
	<!-- foreach标签,可以循环的传入参数值 -->
	<if test="idList != null">
		<foreach collection="idList"  item="id" open="AND id IN (" close=")" separator=",">
			#{id}
		</foreach>
	</if>

</sql>
<select id="findUserList" parameterType="cn.itcast.po.UserCustom" resultType="cn.itcast.po.User">
	select * from user 
	<where>
		<include refid="whereclause"></include>
	</where>	
</select>

2测试

	@Test
	public void testFindUserList() {
		//创建UserMapper对象
		SqlSession sqlSession = sqlSessionFactory.openSession(true) ;
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class) ;
		
		UserCustom userCustom = new UserCustom();
//		User user = new User() ;
//		//user.setSex("1");
//		user.setUsername("小明");
//		userCustom.setUser(user);		
		
		
		List<Integer> idList = new ArrayList<Integer>();
		idList.add(1);
		idList.add(10);
		idList.add(16);
		userCustom.setIdList(idList);
		List<User> list = userMapper.findUserList(userCustom);	
		System.out.println(list);
		sqlSession.close();	
	}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值