mybatis 动态sql语句

介绍

动态 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提供以下标签:


原文出处:/show_1IXwLr3etP.html