动态sql之表单条件查询

264 阅读1分钟

1.使用elementui找到对应的行内查询表单,引入对应的代码并修改

image.png

image.png

2.将分页查询事件稍作修改,改为分页并搜索

image.png

3.完善后端代码

为了变得更加容易维护,后端传入的对象应为可以随意更变,并且不影响实体类,我们应该专门创建一个用来接收搜索表单的java对象

image.png

controller:

@RequestMapping("/selectPageByCondition")
@ResponseBody//将返回的java对象转换为json字符串
public Request selectPage(@RequestParam(defaultValue = "1") Integer currentPage,
                          @RequestParam(defaultValue = "5") Integer pageSize,
                          @RequestBody StudentVo studentVo){
    PageInfo<Student> page =studentServiceImp.findAll(currentPage,pageSize,studentVo);

    val re = new Request(200, "查询数据成功", page);
    return new Request(200, "查询数据成功", page);
}

service:

 public PageInfo<Student> findAll(Integer currentPage, Integer pageSize, StudentVo studentVo) {
        /*分页数据给拦截器*/
        PageHelper.startPage(currentPage,pageSize);
        /*将前端的搜索条件传给dao层做动态sql查询*/
        List<Student> all = studentDao.findAllByCondition(studentVo);
        /*将查询的数据封装到PageInfo中,完成分页参数整合*/
        PageInfo<Student> studentPageInfo = new PageInfo<Student>(all);
        return studentPageInfo;
    }
}

sql:

<sql id="studentAndClazz">
    s.id,s.name,s.age,s.sex,s.student_id,c.id cid,c.name cname
</sql>
<!--自定义返回类型-->
<resultMap id="map" type="com.cjj.pojo.Student" autoMapping="true">
<id column="id" property="id"/>
<result property="name" column="name"/>
<association property="clazz" javaType="com.cjj.pojo.Clazz" >
    <id column="cid" property="id"/>
    <result column="cname" property="name"/>
</association>
</resultMap>
<!--搜索(条件)查询-->
<select id="findAllByCondition" resultMap="map" parameterType="com.cjj.vo.StudentVo">
    select <include refid="studentAndClazz"/> from student s join class c on s.student_id=c.id
    <where>
        <if test="name!=null and name!=''">
           and s.name like concat('%',#{name},'%')
        </if>
        <if test="age!=null and age!=''">
            and s.age=#{age}
        </if>
        <if test="sex!=null and sex!=''">
            and s.sex=#{sex}
        </if>
        <if test="studentId!=null">
            and s.student_id=#{studentId}
        </if>
    </where>
</select>

需求完毕之后,发现不能返回查询所有数据

1.增加查询所有按钮

image.png

2.点击事件

conditionFindStudent为查询的form表单,为了查询到所有内容,必须将此对象作为空对象传递。

image.png