我们在进行查询操作的时候会有根据多个参数来查询的情况,查询语句一样,但是条件不一致,这个时候使用动态sql语句就可以非常方便的帮助我们实现多条件查询,
动态sql中,where标签包裹就是代表数据库中的where关键字:里面用 if 来判断传来的参数,如果参数不为空,就拼接上里面的条件,如果为空就不拼接。注意多参数时 ,dao接口 加上@Param注解,每个参数都加。要不参数无法识别。
下面一个例子(sql在第4步,前面是接收过程):
1. 可以先看一下我的查询页面,是根据姓名,班级组成的多个不同的条件来进行查询的,我们可以只输入姓名查询,也可以只选择班级查询,也可以两个条件都加上,使用动态sql语句的话只需要一条查询语句就可以完成多种不同条件的查询:
2 .controller层接收传来的参数,把所有的条件参数无论是空还是有值的情况都传到我们的控制层接收,timeteach, cnamecid, stuname,接收到这三个参数后调用service层的对应方法:
注意一点,如果传递参数,路径/{XXX}传参XXX 那么@PathVariable("XXX") 每个参数都加,如果对象json格式传参,@RequestBody 基本都适用。@RequestParam("XXX")则而有局限性。这里不加赘述。放入请求头,请求体,那部分里面。
注意前后端分离 情况,是否返回json格式。否则视图解析器会报异常。
@RequestMapping("tostushow")
public String stushow(String uname,String stuname,Integer cnamecid,HttpServletRequest req){
//将接收的参数调用service层的方法
List<Students> list = teachMainService.getStuAll(timeteach, cnamecid, stuname,pageNum,pageSize);
req.setAttribute("list ", list );
return "stushow";
}
3. 多参数注意加@Param注解,要不然参数无法识别 通过service最终到dao层,dao层执行的是mapper映射文件里的sql查询语句,这里要注意的一点是如果是传递多个参数,在dao层需要在参数前面加上@Param(“name”)注解:
public List<Students> selectStuAll(@Param("timeteach") Integer timeteach,@Param("cid") Integer cnamecid,@Param("stuname") String stuname);
1
4.最后就是执行我们的动态sql语句了,
where标签包裹就是代表数据库中的where关键字:里面用 if 来判断传来的参数,如果参数不为空,就拼接上里面的条件,如果为空就不拼接,这样就完成了我们的多条件动态sql查询
<select id="selectStuAll" resultMap="stumap">
SELECT distinct a.stuname,a.stunum,a.stuage,a.stusex,a.sturemarks,a.stuimg,a.stuhome,b.cname,c.timeteach
FROM `students` a left join clazz b on a.stuclazz = b.cid
inner join clazztime c on b.cid = c.timeclzid
<where>
<if test="timeteach != null and timeteach != ‘‘">
and timeteach = #{timeteach}
</if>
<if test="cid != null">
and b.cid = #{cid}
</if>
<if test="stuname != null">
and a.stuname like concat(‘%‘,#{stuname},‘%‘)
</if>
</where>
</select>
原文:https://www.cnblogs.com/nigulasi-yu/p/12158905.html