Mybatis动态SQL之if判断(20)

本文介绍MyBatis中的动态SQL应用案例,演示如何利用if标签实现SQL查询条件的动态拼接,包括用户信息的综合查询及查询总数的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mybatis动态SQL核心:对SQL语句进行灵活操作,通过表达式进行判断,对SQL进行灵活拼接、组装。

一、if判断

1.1、需求

用户信息综合查询列表和用户信息查询列表总数这两个statement的定义使用动态SQL。

1.2、修改UserMapper.xml中的SQL语句

	<!-- 用户信息综合查询
	#{userCustom.sex}:取出pojo包装对象中性别值
	${userCustom.username}:取出pojo包装对象中用户名称
	 -->
	<select id="findUserList" parameterType="UserQueryVo" 
		resultType="UserCustom">
		select * from user 
		<!-- 
		where可以自动去掉条件中的第一个and 
		-->
		<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>
		</where>
		
	</select>
	
	<!-- 用户信息综合查询总数 
	parameterType:指定输入类型和findUserList一样
	resultType:输出结果类型
	-->
	<select id="findUserCount" parameterType="UserQueryVo" resultType="int">
		select count(*) from user
		<!-- 
		where可以自动去掉条件中的第一个and 
		-->
		<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>
		</where>
	</select>

1.3、修改测试代码进行测试

将测试代码中的userCustom去掉进行测试。

	/**
	 * 测试用户信息的综合查询
	 * @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);
	}

生成的SQL语句:

select * from user



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值