6-6 店铺列表展示之Service层的实现及分页的转换

1、编写ShopService接口

public interface ShopService {
	/**
	 * 根据shopCondition分页返回相应店铺列表
	 * @param shopCondition
	 * @param pageIndex 
	 * @param pageSize
	 * @return ShopExecution 因为不仅要返回店铺列表还要返回店铺数量,这个类正好可以满足
	 */
	public ShopExecution getShopList(Shop shopCondition, int pageIndex, int pageSize);
}

2、编写接口实现类

@Service
public class ShopServiceImpl implements ShopService {
	@Override
	public ShopExecution getShopList(Shop shopCondition, int pageIndex, int pageSize) {
		// 前端返回的是页数,但Dao层只认行数,因此需要做转换
		int rowIndex = PageCalculator.calculateRowIndex(pageIndex, pageSize);
		List<Shop> shopList = shopDao.queryShopList(shopCondition, rowIndex, pageSize);
		int count = shopDao.queryShopCount(shopCondition);
		ShopExecution se = new ShopExecution();
		if(shopList != null) {
			se.setShopList(shopList);
			se.setCount(count);
		}else {
			se.setState(ShopStateEnum.INNER_ERROR.getState());
		}
		return se;
	}

}

注意前端返回的是页数pageIndex,但Dao层只认行数rowindex,因此需要做转换

编写工具类PageCalculator

public class PageCalculator {
	public static int calculateRowIndex(int pageIndex,int pageSize) {
		return (pageIndex>0) ? (pageIndex-1)*pageSize : 0;
	}
}

3、编写测试类

public class ShopServiceTest extends BaseTest{
	@Autowired
	private ShopService shopService;
	@Test
	public void testGetShopList() {
		Shop shopCondition = new Shop();
		ShopCategory sc = new ShopCategory();
		sc.setShopCategoryId(1L);
		shopCondition.setShopCategory(sc);
		ShopExecution se = shopService.getShopList(shopCondition, 1, 2);//第一页,每页两条数据
		System.out.println("店铺列表数为"+se.getShopList().size());
		System.out.println("店铺总数为"+se.getCount());
	}
}
	
 

猜你喜欢

转载自blog.csdn.net/weixin_40703303/article/details/89535663