- Mysql分页可使用Limit关键字进行分页查询
了解案例分页原理,即可开始下一步操作
案例分析
我们可在实体类定义两个变量来接收数据
public class PageBean < T> {
private int totalCount;
private List< T> rows;
public int getTotalCount ( ) {
return totalCount;
}
public void setTotalCount ( int totalCount) {
this . totalCount = totalCount;
}
public List< T> getRows ( ) {
return rows;
}
public void setRows ( List< T> rows) {
this . rows = rows;
}
}
定义实体类后,我们需要在BrandMapper类里面编写对应的mybatis方法实现数据接收
@Select ( "select * from tb_brand limit #{begin},#{size}" )
List< Brand> selectByPage ( @Param ( "begin" ) int begin, @Param ( "size" ) int size) ;
@Select ( "select count(*) from tb_brand" )
int selectTotalCount ( ) ;
在BrandService接口中定义分页查询方法
PageBean< Brand> selectByPage ( int currentPage, int pageSize) ;
然后在BrandServiceimpl类里实现BrandServiceimpl接口的BrandServiceimpl方法
@Override
public PageBean< Brand> selectByPage ( int currentPage, int pageSize) {
SqlSession sqlSession = factory. openSession ( ) ;
BrandMapper mapper = sqlSession. getMapper ( BrandMapper. class ) ;
int begin = ( currentPage - 1 ) * pageSize;
int size = pageSize;
List< Brand> rows = mapper. selectByPage ( begin, size) ;
int tocalCount = mapper. selectTotalCount ( ) ;
PageBean< Brand> pageBean = new PageBean < > ( ) ;
pageBean. setRows ( rows) ;
pageBean. setTotalCount ( tocalCount) ;
sqlSession. close ( ) ;
return pageBean;
}
写个BaseServlet类实现servlet优化
public class BaseServlet extends HttpServlet {
@Override
protected void service ( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url = req. getRequestURI ( ) ;
int index = url. lastIndexOf ( '/' ) ;
String methodName = url. substring ( index + 1 ) ;
Class< ? extends BaseServlet > aClass = this . getClass ( ) ;
try {
Method method = aClass. getMethod ( methodName, HttpServletRequest. class , HttpServletResponse. class ) ;
method. invoke ( this , req, resp) ;
} catch ( NoSuchMethodException e) {
e. printStackTrace ( ) ;
} catch ( InvocationTargetException e) {
e. printStackTrace ( ) ;
} catch ( IllegalAccessException e) {
e. printStackTrace ( ) ;
}
}
}
再去Select层里写个BrandServlet类继承BaseServlet类
public class BrandServiceimpl implements BrandService {
SqlSessionFactory factory = SqlSessionFactoryUtils. getSqlSessionFactory ( ) ;
@Override
public PageBean< Brand> selectByPage ( int currentPage, int pageSize) {
SqlSession sqlSession = factory. openSession ( ) ;
BrandMapper mapper = sqlSession. getMapper ( BrandMapper. class ) ;
int begin = ( currentPage - 1 ) * pageSize;
int size = pageSize;
List< Brand> rows = mapper. selectByPage ( begin, size) ;
int tocalCount = mapper. selectTotalCount ( ) ;
PageBean< Brand> pageBean = new PageBean < > ( ) ;
pageBean. setRows ( rows) ;
pageBean. setTotalCount ( tocalCount) ;
sqlSession. close ( ) ;
return pageBean;
}
}