成都网站建设设计

将想法与焦点和您一起共享

动态SQL复杂查询语句

 今天小编就为大家带来一篇有关动态SQL复杂查询语句的文章。小编觉得挺实用的,为此分享给大家做个参考。一起跟随小编过来看看吧。

应县网站制作公司哪家好,找创新互联公司!从网页设计、网站建设、微信开发、APP开发、响应式网站开发等网站项目制作,到程序开发,运营维护。创新互联公司于2013年创立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联公司

多条件查询

普通的sql查询多条判断条件时

select * from emp

where 1=1 and ename = ? and job = ? and sal = ?

当其中一个条件为空时或者未提供会报错

mybatis提供了 if 标签

and ename like concat("%",#{name},"%")

判断失败则不加入sql语句

实例

//map传参

List selectByCondition1(Map searchMap);

//顺序传参

List selectByCondition2(String ename,String job,Double sal);

//对象传参

List selectByCondition3(SearchMap searchMap);

public class SearchMap {

private String name;

private String job;

private Double sal;

}

select * from emp where      ename like concat("%",#{ename},"%")        and job = #{job}        and sal > #{sal}

select * from emp where      ename like concat("%",#{param1},"%")        and job = #{param2}        and sal > #{param3}

select * from emp where      ename like concat("%",#{name},"%")        and job = #{job}        and sal > #{sal}

这样还是存在问题 如果其中第一条判断失败 那么第二条加入 会变成

select * from emp where and job = #{job}多余的and导致出错

可以通过一般方式解决

select * from emp where 1=1

and ename like concat("%",#{name},"%")

and job = #{job}

and sal > #{sal}

为了解决这个问题 mybatis提供了 where标签

select * from emp

and ename like concat("%",#{name},"%")

and job = #{job}

and sal > #{sal}

where标签会自动出掉多余的第一个and或者or

foreach查询

需求

传入多个 id 查询用户信息,用下边两个 sql 实现:

SELECT * FROM USERS WHERE username LIKE '%张%' AND (id =10 OR id =89 OR id=16)

SELECT * FROM USERS WHERE username LIKE '%张%' AND id IN (10,89,16)

这样我们在进行范围查询时,就要将一个集合中的值,作为参数动态添加进来。

这样我们将如何进行参数的传递?

在 QueryVo 中加入一个 List 集合用于封装参数

/**

*

Description: 查询的条件

*/郑州引产手术费用多少钱 https://yiyuan.120ask.com/art/307587.html

public class QueryVo implements Serializable {

private List ids;

public List getIds() {

return ids;

}

public void setIds(List ids) {

this.ids = ids;

}

}

持久层 Dao 接口

/**

* 根据 id 集合查询用户

* @param vo

* @return

*/

List findInIds(QueryVo vo);

持久层 Dao 映射配置

#{uid}

SQL 语句:

select 字段 from user where id in (?)

标签用于遍历集合,它的属性:

collection:代表要遍历的集合元素,注意编写时不要写#{}

open:代表语句的开始部分

close:代表结束部分

item:代表遍历集合的每个元素,生成的变量名

sperator:代表分隔符

1.3.3.1.编写测试方法

@Test

public void testFindInIds() {

QueryVo vo = new QueryVo();

List ids = new ArrayList();

ids.add(41);

ids.add(42);

ids.add(43);

ids.add(46);

ids.add(57);

vo.setIds(ids);

//6.执行操作

List users = userDao.findInIds(vo);

for(User user : users) {

System.out.println(user);

}

}

Mybatis 中简化编写的 SQL 片段 sql冗余

Sql 中可将重复的 sql 提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的。

1 定义代码片段

select * from user

2 引用代码片段

where id = #{uid}

 以上就是动态SQL复杂查询语句的介绍,详细使用情况还得要大家自己使用过才能知道具体要领。如果想阅读更多相关内容的文章,欢迎关注创新互联行业资讯频道!


网页题目:动态SQL复杂查询语句
标题URL:http://chengdu.cdxwcx.cn/article/gcijce.html