MyBatis动态SQL之choose和where的使用示例

首先在以前的user表中,肯定一下表中的数据先
java

在以前的User.xml中添加SQL语句
sql

<select id="selectUserChoose" resultType="User" parameterType="User">
	select * from BSuser where 1=1
		<choose>  //判断用户名,若是为空就判断ID,最后判断密码不为空
			<when test="userName!=null">
				and userName like #{userName}
			</when>
			<when test="id!=0">
				and id =#{id}
			</when>
			
			<otherwise>
				and password is not null
			</otherwise>
		</choose>
	</select>

在测试类中的try内写入代码session

try{
			
			//动态SQL之 choose 与where
			User oneUser=new User();
			oneUser.setUserName("%k%");
			List<User> ap=session.selectList("selectUserChoose",oneUser);
			for(User temp:ap) {		
			System.out.println("用户ID="+temp.getId()+"用户名="+temp.getUserName());
			}

运行,输出结果是测试

  用户ID=2用户名=kobe01spa

用户ID=3用户名=kobe02code

用户ID=8用户名=kobe03xml

执行的SQL代码是select * from user where 1=1 and userName like ? get

//whereio

在User.xml中添加class

<select id="selectUserWhere" resultType="User" parameterType="User">
	select * from user  
		<where>
			<if test="userName!=null">
				and userName like #{userName}
			</if>
			<if test="id!=null">
				and id =#{id}
			</if>
		</where>
</select>

在测试类中写入

try{
			//动态SQL之where
			User oneUser=new User();
			oneUser.setId(10);
			//where标记
			List<User> ap=session.selectList("selectUserWhere",oneUser);
			for(User temp:ap) {		
			System.out.println("用户ID="+temp.getId()+"用户名="+temp.getUserName());
		}

输出的结果为  用户ID=10用户名=1

执行的SQL语句为 select * from jikeuser WHERE id =? 

where智能的去掉了sql语句中id前的and

若在setId前加上 oneUser.setUserName("%k%"); 输出为空

若加上后把id设为3,则输出为  用户ID=3用户名=kobe02

where又智能的去掉了username前的and

如此便利用了MyBais的where动态控制输出了。

以上即是MyBatis动态SQL中的choose和where,欢迎指出不足之处,互相讨论,谢谢。

相关文章
相关标签/搜索