小編這次要給大家分享的是Java如何使用MyBatis框架分頁,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
創(chuàng)新互聯(lián)建站主營(yíng)汕尾網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,成都App定制開發(fā),汕尾h5微信小程序開發(fā)搭建,汕尾網(wǎng)站營(yíng)銷推廣歡迎汕尾等地區(qū)企業(yè)咨詢
初始準(zhǔn)備
1.創(chuàng)建分頁對(duì)象類,方便模塊間傳值
//PageInfo.java import lombok.Data; @Data public class PageInfo { private int pageNo; private int pageSize; }
2.定義DAO層接口
import org.apache.ibatis.session.RowBounds; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserMapper { User selectByUser(User user); ListselectAll(); List selectByPageInfo(PageInfo info); List selectByInterceptor(PageInfo info); List selectByRowBounds(RowBounds rowBounds); }
3.mapper中定義結(jié)果集合BaseResult
一、原始切分:最原始方法,不建議使用
1.mapper代碼:查詢所有數(shù)據(jù)
2.業(yè)務(wù)層代碼:利用List的subList()方法對(duì)數(shù)據(jù)進(jìn)行切片
public ListfindByAll(PageInfo info) { List users = userMapper.selectAll(); return users.subList(info.getPageNo(), info.getPageSize()); }
3.控制層代碼
@RequestMapping(value = "/userlist_1", method = RequestMethod.GET) @ResponseBody public Result findUserBySubList(PageInfo info) { Listusers = userService.findByAll(info); if(users.size() == 0) { return ResultGenerator.genFailResult("未查找到用戶"); } return ResultGenerator.genSuccessResult(users); }
二、LIMIT關(guān)鍵字
1.mapper代碼:利用limit關(guān)鍵字實(shí)現(xiàn)分頁
2.業(yè)務(wù)層直接調(diào)用
public ListfindByPageInfo(PageInfo info) { return userMapper.selectByPageInfo(info); }
3.控制層直接調(diào)用
三、RowBounds實(shí)現(xiàn)分頁
1.在DAO層定義好所要傳輸?shù)姆猪撔畔?,類型為RowBounds
2.mapper層:查詢所有數(shù)據(jù)
3.業(yè)務(wù)層:將PageInfo信息封裝成RowBounds,調(diào)用DAO層方法
public ListfindByRowBounds(PageInfo info) { return userMapper.selectByRowBounds(new RowBounds(info.getPageNo(), info.getPageSize())); }
4.控制層直接調(diào)用
四、MyBatis的Interceptor實(shí)現(xiàn):實(shí)現(xiàn)復(fù)雜,需要明白MyBatis的實(shí)現(xiàn)
1.創(chuàng)建Interceptor
import org.apache.ibatis.executor.parameter.ParameterHandler; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.SystemMetaObject; import java.sql.Connection; import java.util.Properties; /** * 利用MyBatis攔截器進(jìn)行分頁 * * @Intercepts 說明是一個(gè)攔截器 * @Signature 攔截器的簽名 * type 攔截的類型 四大對(duì)象之一( Executor,ResultSetHandler,ParameterHandler,StatementHandler) * method 攔截的方法 * args 參數(shù),高版本需要加個(gè)Integer.class參數(shù),不然會(huì)報(bào)錯(cuò) * */ @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})}) public class DefinedPageInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { //獲取StatementHandler,默認(rèn)的是RoutingStatementHandler StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); //獲取StatementHandler的包裝類 MetaObject metaObject = SystemMetaObject.forObject(statementHandler); //分隔代理對(duì)象 while (metaObject.hasGetter("h")) { Object obj = metaObject.getValue("h"); metaObject = SystemMetaObject.forObject(obj); } while (metaObject.hasGetter("target")) { Object obj = metaObject.getValue("target"); metaObject = SystemMetaObject.forObject(obj); } //獲取查看接口映射的相關(guān)信息 MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement"); String mapId = mappedStatement.getId(); //攔截以ByInterceptor結(jié)尾的請(qǐng)求,統(tǒng)一實(shí)現(xiàn)分頁 if (mapId.matches(".+ByInterceptor$")) { System.out.println("LOG:已觸發(fā)分頁攔截器"); //獲取進(jìn)行數(shù)據(jù)庫(kù)操作時(shí)管理參數(shù)的Handler ParameterHandler parameterHandler = (ParameterHandler) metaObject.getValue("delegate.parameterHandler"); //獲取請(qǐng)求時(shí)的參數(shù) PageInfo info = (PageInfo) parameterHandler.getParameterObject(); //獲取原始SQL語句 String originalSql = (String) metaObject.getValue("delegate.boundSql.sql"); //構(gòu)建分頁功能的SQL語句 String sql = originalSql.trim() + " limit " + info.getPageNo() + ", " + info.getPageSize(); metaObject.setValue("delegate.boundSql.sql", sql); } //調(diào)用原對(duì)象方法,進(jìn)入責(zé)任鏈下一級(jí) return invocation.proceed(); } @Override public Object plugin(Object target) { //生成Object對(duì)象的動(dòng)態(tài)代理對(duì)象 return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { //如果分頁每頁數(shù)量是統(tǒng)一的,可以在這里進(jìn)行統(tǒng)一配置,也就無需再傳入PageInfo信息了 } }
2.將Interceptor添加至MyBatisConfig中,這里采用JavaConfig的方式
@Bean public SqlSessionFactoryBean sqlSession() { SqlSessionFactoryBean sqlSession = new SqlSessionFactoryBean(); sqlSession.setDataSource(dataSource()); try { Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"); sqlSession.setMapperLocations(resources); //配置自定義的Interceptro作為MyBatis的Interceptor,完成分頁操作 DefinedPageInterceptor definedPageInterceptor = new DefinedPageInterceptor(); sqlSession.setPlugins(new Interceptor[]{definedPageInterceptor}); return sqlSession; } catch (IOException e) { e.printStackTrace(); } return null; }
3.DAO層接口方法名需要和代碼中自定義的".+ByInterceptor$"正則表達(dá)式相匹配,mapper的書寫依然是查詢所有數(shù)據(jù)
4.業(yè)務(wù)層直接調(diào)用
5.控制層直接調(diào)用
五、開源項(xiàng)目PageHelper實(shí)現(xiàn):本質(zhì)還是自己封裝了個(gè)Interceptor
1.引入PageHelper的jar包
com.github.pagehelper pagehelper 5.1.10
2.配置PageInterceptor
public PageInterceptor initPageInterceptor(){ PageInterceptor pageInterceptor = new PageInterceptor(); Properties properties = new Properties(); //設(shè)置數(shù)據(jù)庫(kù)類型 properties.setProperty("helperDialect", "MySQL"); //該參數(shù)默認(rèn)為false //設(shè)置為true時(shí),會(huì)將RowBounds第一個(gè)參數(shù)offset當(dāng)成pageNum頁碼使用 //和startPage中的pageNum效果一樣 properties.setProperty("offsetAsPageNum", "true"); //該參數(shù)默認(rèn)為false //設(shè)置為true時(shí),使用RowBounds分頁會(huì)進(jìn)行count查詢 properties.setProperty("rowBoundsWithCount", "true"); pageInterceptor.setProperties(properties); return pageInterceptor; } @Bean public SqlSessionFactoryBean sqlSession() { SqlSessionFactoryBean sqlSession = new SqlSessionFactoryBean(); sqlSession.setDataSource(dataSource()); try { Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"); sqlSession.setMapperLocations(resources); //配置PageHelper作為MyBatis的Interceptor,完成分頁操作 PageInterceptor pageInterceptor = this.initPageInterceptor(); //配置自定義的Interceptro作為MyBatis的Interceptor,完成分頁操作 DefinedPageInterceptor definedPageInterceptor = new DefinedPageInterceptor(); sqlSession.setPlugins(new Interceptor[]{pageInterceptor, definedPageInterceptor}); return sqlSession; } catch (IOException e) { e.printStackTrace(); } return null; }
3.mapper依然是查詢所有數(shù)據(jù)
4.為DAO層再封裝一次方法
@Repository public class PageHelperHandler { @Autowired private SqlSessionFactory sqlSessionFactory; public ListfindByPageHelper(PageInfo info) { SqlSession session = sqlSessionFactory.openSession(); PageHelper.startPage(info.getPageNo(), info.getPageSize()); //寫到要使用到的類名和方法名 List users = session.selectList("cn.edu.yau.mapper.UserMapper.selectAll"); return users; } }
6.業(yè)務(wù)層直接調(diào)用Handler
7.控制層直接調(diào)用
看完這篇關(guān)于Java如何使用MyBatis框架分頁的文章,如果覺得文章內(nèi)容寫得不錯(cuò)的話,可以把它分享出去給更多人看到。