在现在写的项目中用到了动态查询,就是给出数个查询条件,在其中选择自己需要的查询条件,如果不需要则不填,根据选择的条件实现查询语句
前台页面不再赘述,无非是表单,不过顺便一提,表单为空时不代表该值为null,详情可见之前博文
JSP页面传值为空格而不为null以及List为空不为null
之后配置相应Mapper,只要对照相应参数便可,以下是对应Mapper.xml
<select id="queryByConditions" resultMap="pw.News">
SELECT `id`,`title`,`author`,`type`,`time`
FROM `t_news`
<where>
id != 0
<if test="title != null">
AND `title`
LIKE concat('%',#{title},'%')
</if>
<if test="content != null">
AND `content`
LIKE concat('%',#{content},'%')
</if>
<if test="author != null">
AND `author`
LIKE concat('%',#{author},'%')
</if>
<if test="type != null">
AND `type` = #{type}
</if>
</where>
ORDER BY `time` DESC
</select>
以上
本文介绍了一种使用MyBatis实现动态查询的方法,通过在前端提供可选查询条件,并结合后端MyBatis的XML配置文件实现灵活的SQL拼接,支持按标题、内容、作者及类型等多个维度进行搜索。

1696

被折叠的 条评论
为什么被折叠?



