今天遇到一个问题,就是需要根据前端页面发送的条件查询数据库记录,但是前端发送的条件是不确定的。如果使用mybatis的xml方法可以使用if标签灵活的添加判断条件,但是现在我使用的就是单纯的sql。
我是这样解决的:
使用case when 语句可以完成这样的sql拼接。值得注意的是判断的时候用的是is null/is not null,而不要使用=/!=
昨天忘了判断空字符串,修改如下:
之前是直接使用sql实现,今天使用java的方式实现动态添加查询条件:
操作如下:
(1)首先创建一个类封装查询条件
(2)然后创建一个类封装查询方法
public class CustomerPartnerDaoP { public String selectPartner( GetParmeter getParmeter) { StringBuilder sql = new StringBuilder(); String ciname= getParmeter.getCiname(); String citelephone= getParmeter.getCitelephone(); int cisex= getParmeter.getCisex(); String cibirthday= getParmeter.getCibirthday(); String cizipcode= getParmeter.getCizipcode(); String cifax= getParmeter.getCifax(); String ciofficename= getParmeter.getCiofficename(); String ciareacode= getParmeter.getCiareacode(); String ciareafullname= getParmeter.getCiareafullname(); String ciaddress= getParmeter.getCiaddress(); String cimodifiedtime= getParmeter.getCimodifiedtime(); sql.append("select ciid,ciname,citelephone,cisex,cibirthday,cizipcode,cifax,ciofficename,ciareacode ," + "ciareafullname,ciaddress,cimodifiedtime from qb_customer_info where 1=1 "); if(!Objects.isNull(ciname) && !"".equals(ciname)){ sql.append(" and ciname").append("=").append("'"+ciname+"'"); } if(!Objects.isNull(citelephone) && !"".equals(citelephone)){ sql.append(" and citelephone").append("=").append("'"+citelephone+"'"); } if(!Objects.isNull(cisex) && !"".equals(cisex)){ sql.append(" and cisex").append("=").append(cisex); } if(!Objects.isNull(cibirthday) && !"".equals(cibirthday)){ sql.append(" and cibirthday").append("=").append("'"+cibirthday+"'"); } if(!Objects.isNull(cizipcode) && !"".equals(cizipcode)){ sql.append(" and cizipcode").append("=").append("'"+cizipcode+"'"); } if(!Objects.isNull(cifax) && !"".equals(cifax)){ sql.append(" and cifax").append("=").append("'"+cifax+"'"); } if(!Objects.isNull(ciofficename) && !"".equals(ciofficename)){ sql.append(" and ciofficename").append("=").append("'"+ciofficename+"'"); } if(!Objects.isNull(ciareacode) && !"".equals(ciareacode)){ sql.append(" and ciareacode").append("=").append("'"+ciareacode+"'"); } if(!Objects.isNull(ciareafullname) && !"".equals(ciareafullname)){ sql.append(" and ciareafullname").append("=").append("'"+ciareafullname+"'"); } if(!Objects.isNull(ciaddress) && !"".equals(ciaddress)){ sql.append(" and ciaddress").append("=").append("'"+ciaddress+"'"); } if(!Objects.isNull(cimodifiedtime) && !"".equals(cimodifiedtime)){ sql.append(" and cimodifiedtime").append("=").append("'"+cimodifiedtime+"'"); } return sql.toString(); }
(3)使用@SelectProvider方法调用
如有不同意见,欢迎指正!