目标:编写一个springBoot接口
要求:做一个有分页,有排序的模糊查询接口
步骤
第一步
先在dao层的Mapper目录下完成接口的编写,由于查询到的结果是很多条数据,所以返回类型List<>,参数通过Map集合来传递;
查询到的每一条数据的具体内容放进map集合中,list存放所有查询到的数据
List<Map<String, Object>> selectByAny(Map<String, Object> params);
int seletcAll(Map<String, Object> params);
第二 步
某一页要显示的数据
在resources文件里面完成Mapper.xml的编写
需要传递的参数有:用户模糊查询的内容,可能为title,可能为author
<if test="title != null and title != ''">
AND title LIKE CONCAT('%',#{title},'%')
</if>
<if test="author != null and author != ''">
AND author LIKE CONCAT('%',#{author},'%')
</if>
还有判断是否有排序及正确排序:
ASC和DESC
<if test="order != null and order != ''">
ORDER BY ${prop}
<if test="order == 'descending'">DESC</if>
</if>
最后一个功能:分页
<if test="pageLimit != 0">
LIMIT #{startIndex},#{pageLimit}
</if>
<select id="selectByAny" parameterType="Map" resultType="Map">
<select id="selectByAny" parameterType="Map" resultType="Map">
SELECT
id,
title,
author,
DATE_FORMAT(datas, '%Y.%m.%d %H:%I:%S'),
user_create,
DATE_FORMAT(utc_create, '%Y.%m.%d %H:%I:%S') utcCreate,
user_modify userModifym
FROM
xiaosa
<where>
<if test="title != null and title != ''">
AND title LIKE CONCAT('%',#{title},'%')
</if>
<if test="author != null and author != ''">
AND author LIKE CONCAT('%',#{author},'%')
</if>
<if test="id != null and id != ''">
AND id = #{id}
</if>
</where>
<if test="order != null and order != ''">
ORDER BY ${prop} <if test="order == 'descending'">DESC</if>
</if>
<if test="pageLimit != 0">
LIMIT #{startIndex},#{pageLimit}
</if>
</select>
模糊查询得到的所有数据
还有一个查询总记录数的:
用的嵌套查询:
第一步:
查到模糊查询需要查的所有数据:
SELECT
id,
title,
author,
DATE_FORMAT(datas, '%Y.%m.%d %H:%I:%S'),
user_create,
DATE_FORMAT(utc_create, '%Y.%m.%d %H:%I:%S') utcCreate,
user_modify userModify
FROM
xiaosa
<where>
<if test="title != null and title != ''">
AND title LIKE CONCAT('%',#{title},'%')
</if>
<if test="author != null and author != ''">
AND author LIKE CONCAT('%',#{author},'%')
</if>
<if test="id != null and id != ''">
AND id = #{id}
</if>
</where>
第二步:
计算条数
SELECT
COUNT( * )
FROM
x
</select>
x为第一步查到的数据表的别名
坑:嵌套查询一定要给内部表去别名
<select id="seletcAll