您的位置:首页 > 数据库

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

2016-09-20 20:22 288 查看
摘要: MyBatis动态SQL的choose和where的例子

首先在之前的user表中,确定一下表中的数据先



在之前的User.xml中添加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内写入代码

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用户名=kobe01

用户ID=3用户名=kobe02

用户ID=8用户名=kobe03

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

//where

在User.xml中添加

<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,欢迎指出不足之处,互相讨论,谢谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息