介绍
动态 SQL 是 MyBatis 的强大特性之一
官网:
https://mybatis.org/mybatis-3/zh/dynamic-sql.html
提出问题
在查询时,经常需要动态生成sql语句,如下:
public String query(String name,Integer age,String sex){
List list=new ArrayList();
String sql=" select name,age,sex from user where 1=1 ";
if(name!=null && !"".equals(name)){
sql=sql+" and name like ?";
list.add("%"+name+"%");
}
if(age!=null){
sql=sql+" and age=?";
list.add(age);
}
if(sex!=null && !"".equals(sex)){
sql=sql+" and sex=?";
list.add(sex);
}
}
这种动态拼装sql的方式,非常麻烦,甚至需要有 1=1
mybatis动态sql
为了解决上面的问题,mybatis提供以下标签:
<if>,相当于 javaif语句
https://www.malaoshi.top/show_1EF6ZihC0jVO.html<where>,相当于sql中的where关键字
https://www.malaoshi.top/show_1EF6ZihC0jVO.html<set>,相当于sql中的set关键字
https://www.malaoshi.top/show_1IXwLOmOIO.html<foreach>,相当于 javafor语句
https://www.malaoshi.top/show_1EF6a24gyYqr.html
https://www.malaoshi.top/show_1EF6a2CVAEI1.html