动态SQl
mybatis核心 对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接、组装。对查询条件进行判断,如果输入参数不为空才进行查询条件拼接。
1、if
1
2
3 select * from user
4 where 1=1
5
6 and id=#{id}
7
8
9 and username like ‘%${username}%’
10
11
2、Where
上面的配置也可以按如下来写:
复制代码
1
2 select * from user
3
4
5 and id=#{id}
6
7
8 and username like ‘%${username}%’
9
10
11
可以自动处理第一个and。
3、foreach
向sql传递数组或List,mybatis使用foreach解析,如下:
如果我们需要传入多个ID来查询多个用户的信息,这也就可以使用foreach。我们先考虑下如果只写sql语句是如下:
1 SELECT * FROM USERS WHERE username LIKE ‘%张%’ AND (id =10 OR id =89 OR id=16)
2 SELECT * FROM USERS WHERE username LIKE ‘%张%’ id IN (10,89,16)
index:为