MyBatis动态SQL之choose和where的使用示例
2016-09-20 20:22
288 查看
摘要: MyBatis动态SQL的choose和where的例子
首先在之前的user表中,确定一下表中的数据先
在之前的User.xml中添加SQL语句
在测试类中的try内写入代码
运行,输出结果是
用户ID=2用户名=kobe01
用户ID=3用户名=kobe02
用户ID=8用户名=kobe03
执行的SQL代码是select * from user where 1=1 and userName like ?
//where
在User.xml中添加
在测试类中写入
输出的结果为 用户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,欢迎指出不足之处,互相讨论,谢谢。
首先在之前的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,欢迎指出不足之处,互相讨论,谢谢。
相关文章推荐
- MyBatis-动态SQL的if、choose、when、otherwise、trim、where、set、foreach使用
- MyBatis-动态SQL的if、choose、when、otherwise、trim、where、set、foreach使用
- MyBatis动态SQL之一使用 if 标签和 choose标签
- mybatis-使用where动态拼接sql
- SSM框架day02-MyBatis——036 动态SQL-where、037 动态SQL-choose、038 动态SQL-foreach数组、039 动态SQL-foreachList
- MyBatis代码实例系列-06:Mybatis动态SQL标签(一)---if、where、set、trim、choose
- mybatis-动态sql-if,choose,when,otherwis,trim,where,set,foreach,test,bind
- Mybatis动态SQL之if、choose、where、set、trim、foreach标记实例详解
- Mybatis动态SQL——if、choose、where、set、trim、foreach标记实例
- Mybatis中动态SQL(if,where,foreach 的使用)
- Mybatis中动态SQL(if,where,foreach 的使用)
- mybatis的动态SQL(三)where、set、trim标签的使用
- mybatis动态sql中where标签的使用
- mybatis 之 动态sql(一)choose标签的使用
- MyBatis动态SQL之一使用 if 标签和 choose标签
- mybatis动态sql中where标签的使用
- MyBatis动态SQL之if的使用示例
- mybatis-使用choose动态拼接sql
- mybatis的动态SQL(二)choose标签的使用
- Mybatis中动态SQL,if,where,foreach的使用教程详解