基于mybatis与PageHelper插件实现条件分页查询(3.19)
实现商品分页例子
需要先引入mybatis与pagehelper插件,在pom.xml里
<!-- Mybatis -->
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.3</version>
</dependency><!--分页插件PageHelper-->
<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.4.7</version>
</dependency>
利用三层架构分别实现对应代码。
Controller层
@Slf4j
@RestController
@RequestMapping("/products")
public class ProductController {@Autowiredprivate ProductService productService;/*** 分页条件查询商品*/@GetMappingpublic Result page(ProductQueryParam queryParam) {log.info("条件分页查询, {}", queryParam);PageBean pageBean = productService.page(queryParam);return Result.success(pageBean);}
}
Service层
public interface ProductService {PageBean page(ProductQueryParam queryParam);
}
ServiceImpl层
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {@Autowiredprivate ProductMapper productMapper;//条件分页查询商品数量@Overridepublic PageBean page(ProductQueryParam queryParam) {PageHelper.startPage(queryParam.getPage(), queryParam.getPageSize());Page<Product> productList = productMapper.page(queryParam);return new PageBean(productList.getTotal(), productList.getResult());}
}
Mapper层
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {//条件分页查询商品数量@Overridepublic PageBean page(ProductQueryParam queryParam) {PageHelper.startPage(queryParam.getPage(), queryParam.getPageSize());Page<Product> productList = productMapper.page(queryParam);return new PageBean(productList.getTotal(), productList.getResult());}
}
Mapper.xml层
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.ProductMapper"><!--条件分页查询--><select id="page" resultType="com.itheima.pojo.Product">select p.*, b.name as brandName from tb_product p left join tb_brand b on p.brand_id = b.id<where><if test="name != null and name != ''">name like concat('%', #{name} ,'%')</if><if test="brandId != null">and brand_id = #{brandId}</if><if test="publishStatus != null">and publish_status = #{publishStatus}</if><if test="verifyStatus != null">and verify_status = #{verifyStatus}</if></where>order by create_time desc</select></mapper>