- 在mapper接口中定义两个方法
// 根据条件查询出总数目
Long queryPage(BrandQuery brandQuery);
//符合条件的所有数据
List<Brand> QueryRows(BrandQuery brandQuery);
使用的是mybatisplus,需要自己写sql
queryPage代码
<select id="queryPage" parameterType="brandQuery" resultType="long">
select count(*)
from t_brand b left join t_product_type p on b.productType = p.id
<where>
//判断是否有传入条件 有则查询拼接
<if test="keyword != null and keyword != ''">
b.englishName like CONCAT('%',#{keyword},'%')
or b.name like CONCAT('%',#{keyword},'%')
</if>
</where>
</select>
QueryRows代码
<select id="QueryRows" parameterType="brandQuery" resultMap="QueryMap">
SELECT
b.*,
p.name pname,
P.id pid
FROM t_brand b LEFT JOIN t_product_type p on b.productType = p.id
<include refid="brandSql"/>
limit ${current},${rows}
</select>
<sql id="brandSql">
<where>
<if test="keyword != null and keyword != ''">
b.englishName like CONCAT('%',#{keyword},'%')
or b.name like CONCAT('%',#{keyword},'%')
</if>
</where>
</sql>
- baseQuery
//关键字
private String keyword;
//当前页
private Integer page = 1;
//当前总页数
private Integer rows = 10;
private Integer current = 0;
public void setCurrent(Integer current) {
this.current = current;
}
//分页从第条开始
public Integer getCurrent() {
return (page - 1)*rows;
}
- pageList
private long total;
private List<T> rows = new ArrayList<>();
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
}
@Override
public String toString() {
return "PageList{" +
"total=" + total +
", rows=" + rows +
'}';
}
//提供有参构造方法,方便测试
public PageList(long total, List<T> rows) {
this.total = total;
this.rows = rows;
}
//除了有参构造方法,还需要提供一个无参构造方法
public PageList() {
}
- service层代码
@Override
public PageList<Brand> QueryKeyWordBrand(BrandQuery brandQuery) {
//定义一个pageList 对象
PageList pageList = null;
//先查询出符合条件的条数
Long count = baseMapper.queryPage(brandQuery);
System.out.println(count);
//先判断是否有符合条件得
if (count>0){
List<Brand> brands = baseMapper.QueryRows(brandQuery);
//创建pageList 对象
pageList = new PageList<>(count,brands);
return pageList;
}else {
return pageList = new PageList();
}
}
- controller层直接返回
@RequestMapping(value = "/json", method = RequestMethod.POST)
public PageList<Brand> json(@RequestBody BrandQuery query) {
System.out.println(query);
return brandService.QueryKeyWordBrand(query);
}