赞
踩
mybatis sql查询动态标签消除 and 和 or的方法
消除 and 和 or的方法有以下两种:
例子: user 表
id | name | age | sex | hobby | height | weight | score | school |
---|---|---|---|---|---|---|---|---|
1 | 小米 | 18 | 男 | 足球 | 178 | 80 | A | 北大 |
2 | 小红 | 15 | 女 | 游泳 | 152 | 40 | B | 北大 |
3 | 小美 | 18 | 女 | 篮球 | 162 | 50 | B | 华大 |
4 | 小军 | 19 | 男 | 游泳 | 182 | 60 | C | 没有读书 |
成员4人,评4个奖项
1、可以查询全部
2、也可以按照奖项查询(多个奖项查询)
3、按照年龄排序
4、同时也可以根据爱好种类查询
需要掌握的内容:
<where> 标签的使用
<if test> 标签的使用
<select id="getUser" resultType="user" parameterType="map">
select * from user where
<if test="id != null">
id = #{id}
</if>
<if test="name!= null">
and name = #{name}
</if>
</select>
当id==null,name!=null的时候,SQL语句变成:select * from user where and name = #{name}
<select id="getStudents" resultType="student" parameterType="map">
select * from mybatis_test.student
<where>
<if test="id != null">
id = #{id}
</if>
<if test="name!= null">
and name = #{name}
</if>
</where>
</select>
where标签会在sql语句中添加where。
where后面的语句以and或者or开头的时候,where标签会自动删除开头的and和or
<select id="getUser" resultType="user" parameterType="map">
select * from user
where 1 = 1
<if test="id != null">
and id = #{id}
</if>
<if test="name!= null">
and name = #{name}
</if>
</select>
以上的案例可以看出 是and或者or开头的时候,where标签会自动删除开头的and和or
但是如果是以下案例,就没办法消除
因为奖项是组合判断,如果同时查找满足‘或’条件的两个奖项,需要判断比较麻烦
<select id="getStudents" resultType="student" parameterType="map">
select * from mybatis_test.student
<where>
<if test="id != null">
id = #{id}
</if>
and (
<if test="isGanqiangj">
(sex = '男' and age >= 18 and score >= 'A')
</if>
<if test="isRoumeigj">
or (sex = '女' and age >= 18 and score >= 'B')
</if>
)
</where>
</select>
该案例,很明显标签没办法帮忙我们解决问题,所以 1=0 登场了
<select id="getStudents" resultType="student" parameterType="map">
select * from mybatis_test.student
<where>
<if test="id != null">
id = #{id}
</if>
and (
1 = 0 or
<if test="isGanqiangj">
(sex = '男' and age >= 18 and score >= 'A')
</if>
<if test="isRoumeigj">
or (sex = '女' and age >= 18 and score >= 'B')
</if>
)
</where>
</select>
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。