模糊查询+动态(多条件)查询(ssm)

模糊查询与动态查询是一些管理类必须的功能之一,刚好今天做了这一个功能,就总结一下

我是在ssm框架下的,环境配置省略 首先是dao.xml也就是sql语句

<select id="fine"  resultType="cn.edu.model.Staff">
        select * from  staff
        <where>
--         模糊查询
        <if test="keyWords != null and keyWords != ">
            and concat(id,name,sex,number,age,workAge) like  "%"#{keyWords}"%"
        </if>
--         动态查询
        <if test="name != null and name != ">
            and name like "%"#{name}"%"
        </if>
        <if test="id != null and id != ">
            and id=#{id}
        </if>
        <if test="number != null and number != ">
            and number=#{number}
        </if>
        </where>
    </select>

还有的用where 1=1然后判断,这里说一下< where > 标签,这个标签能自动识别and或or和判断 concat 是MySQL语句里面的,功能是连接语句什么的,具体想要了解的话可以自己去查一下 , ()括号里是列的属性,可以实现多属性的模糊查询,如果只有一个属性的话,就不需要用到的这个 直接 属性 like %字段%

< if >是动态查询的核心,很好理解

Service也不写的,直接实现dao就可以了 接下来的controller

if (value != null && !"".equals(value)){
    if ("name".equals(type)){
        staff.setName(value);
    }else if ("id".equals(type)) {
        if ("id".equals(type)) {
            try {
                Integer id = Integer.valueOf(value);
                staff.setId(id);
                staff.setMark(false);
            } catch (Exception e) {
            }
        }
    }else if ("number".equals(type)) {
        staff.setNumber(value);
    } else if ("keyWords".equals(type)) {
        staff.setKeyWords(value);
    }

以上是核心代码,需要传入type和value的值

下面是jsp

<div class="text-c">
    <form action="/staff/getAll" class="form form-horizontal">
        <select class="select-box inline" style="width:100px" name="type" size="1">
        <option value="keyWords">关键字</option>
        <option value="id">id</option>
        <option value="name">姓名</option>
        <option value="number">身份证号</option>
    </select>&nbsp;
        <input type="text" value= "${value}" class="input-text" style="width:250px" placeholder="请输入"  name="value">&nbsp;
        <input type="submit" class="btn btn-success Hui-iconfont radius" name="" value="&#xe665;搜员工">
    </form>
</div>
经验分享 程序员 微信小程序 职场和发展