實現商品分頁例子
? ? ? ? 需要先引入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>