日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

mybatis 分页需要的jar包下载_牛逼哄哄的PageHelper分页插件到底牛在哪里?

發(fā)布時(shí)間:2025/4/5 编程问答 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mybatis 分页需要的jar包下载_牛逼哄哄的PageHelper分页插件到底牛在哪里? 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

你知道的越多,不知道的就越多,業(yè)余的像一棵小草!

你來(lái),我們一起精進(jìn)!你不來(lái),我和你的競(jìng)爭(zhēng)對(duì)手一起精進(jìn)!

編輯:業(yè)余草

urlify.cn/z2IFn2

推薦:https://www.xttblog.com/?p=5116

PageHelper是一款好用的開源免費(fèi)的Mybatis第三方物理分頁(yè)插件,其實(shí)我并不想加上好用兩個(gè)字,但是為了表?yè)P(yáng)插件作者開源免費(fèi)的崇高精神,我毫不猶豫的加上了好用一詞作為贊美。

原本以為分頁(yè)插件,應(yīng)該是很簡(jiǎn)單的,然而PageHelper比我想象的要復(fù)雜許多,它做的很強(qiáng)大,也很徹底,強(qiáng)大到使用者可能并不需要這么多功能,徹底到一參可以兩用。但是,我認(rèn)為,作為分頁(yè)插件,完成物理分頁(yè)任務(wù)是根本,其它的很多智能并不是必要的,保持它夠傻夠憨,專業(yè)術(shù)語(yǔ)叫stupid,簡(jiǎn)單就是美。

我們將簡(jiǎn)單介紹PageHelper的基本使用和配置參數(shù)的含義,重點(diǎn)分析PageHelper作為Mybatis分頁(yè)插件的實(shí)現(xiàn)原理。

1.?PageHelper的maven依賴及插件配置

com.github.pagehelper pagehelper 4.1.6

PageHelper除了本身的jar包外,它還依賴了一個(gè)叫jsqlparser的jar包,使用時(shí),我們不需要單獨(dú)指定jsqlparser的maven依賴,maven的間接依賴會(huì)幫我們引入。

上面是PageHelper官方給的配置和注釋,雖然寫的很多,不過(guò)確實(shí)描述的很明白。

dialect:標(biāo)識(shí)是哪一種數(shù)據(jù)庫(kù),設(shè)計(jì)上必須。

offsetAsPageNum:將RowBounds第一個(gè)參數(shù)offset當(dāng)成pageNum頁(yè)碼使用,這就是上面說(shuō)的一參兩用,個(gè)人覺得完全沒必要,offset = pageSize * pageNum就搞定了,何必混用參數(shù)呢?

rowBoundsWithCount:設(shè)置為true時(shí),使用RowBounds分頁(yè)會(huì)進(jìn)行count查詢,個(gè)人覺得完全沒必要,實(shí)際開發(fā)中,每一個(gè)列表分頁(yè)查詢,都配備一個(gè)count數(shù)量查詢即可。

reasonable:value=true時(shí),pageNum小于1會(huì)查詢第一頁(yè),如果pageNum大于pageSize會(huì)查詢最后一頁(yè) ,個(gè)人認(rèn)為,參數(shù)校驗(yàn)在進(jìn)入Mybatis業(yè)務(wù)體系之前,就應(yīng)該完成了,不可能到達(dá)Mybatis業(yè)務(wù)體系內(nèi)參數(shù)還帶有非法的值。

這么一來(lái),我們只需要記住 dialect = mysql 一個(gè)參數(shù)即可,其實(shí),還有下面幾個(gè)相關(guān)參數(shù)可以配置。

autoDialect:true or false,是否自動(dòng)檢測(cè)dialect。

autoRuntimeDialect:true or false,多數(shù)據(jù)源時(shí),是否自動(dòng)檢測(cè)dialect。

closeConn:true or false,檢測(cè)完dialect后,是否關(guān)閉Connection連接。

上面這3個(gè)智能參數(shù),不到萬(wàn)不得已,我們不應(yīng)該在系統(tǒng)中使用,我們只需要一個(gè)dialect = mysql 或者 dialect = oracle就夠了,如果系統(tǒng)中需要使用,還是得問問自己,是否真的非用不可。

2.?PageHelper源碼分析

@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))public class PageHelper implements Interceptor { //sql工具類 private SqlUtil sqlUtil; //屬性參數(shù)信息 private Properties properties; //配置對(duì)象方式 private SqlUtilConfig sqlUtilConfig; //自動(dòng)獲取dialect,如果沒有setProperties或setSqlUtilConfig,也可以正常進(jìn)行 private boolean autoDialect = true; //運(yùn)行時(shí)自動(dòng)獲取dialect private boolean autoRuntimeDialect; //多數(shù)據(jù)源時(shí),獲取jdbcurl后是否關(guān)閉數(shù)據(jù)源 private boolean closeConn = true; //緩存 private Map urlSqlUtilMap = new ConcurrentHashMap(); private ReentrantLock lock = new ReentrantLock();// ...}

上面是官方源碼以及源碼所帶的注釋,我們?cè)傺a(bǔ)充一下。

SqlUtil:數(shù)據(jù)庫(kù)類型專用sql工具類,一個(gè)數(shù)據(jù)庫(kù)url對(duì)應(yīng)一個(gè)SqlUtil實(shí)例,SqlUtil內(nèi)有一個(gè)Parser對(duì)象,如果是mysql,它是MysqlParser,如果是oracle,它是OracleParser,這個(gè)Parser對(duì)象是SqlUtil不同實(shí)例的主要存在價(jià)值。執(zhí)行count查詢、設(shè)置Parser對(duì)象、執(zhí)行分頁(yè)查詢、保存Page分頁(yè)對(duì)象等功能,均由SqlUtil來(lái)完成。

SqlUtilConfig:Spring Boot中使用,忽略。

autoRuntimeDialect:多個(gè)數(shù)據(jù)源切換時(shí),比如mysql和oracle數(shù)據(jù)源同時(shí)存在,就不能簡(jiǎn)單指定dialect,這個(gè)時(shí)候就需要運(yùn)行時(shí)自動(dòng)檢測(cè)當(dāng)前的dialect。

Map urlSqlUtilMap:它就用來(lái)緩存autoRuntimeDialect自動(dòng)檢測(cè)結(jié)果的,key是數(shù)據(jù)庫(kù)的url,value是SqlUtil。由于這種自動(dòng)檢測(cè)只需要執(zhí)行1次,所以做了緩存。

ReentrantLock lock:這個(gè)lock對(duì)象是比較有意思的現(xiàn)象,urlSqlUtilMap明明是一個(gè)同步ConcurrentHashMap,又搞了一個(gè)lock出來(lái)同步ConcurrentHashMap做什么呢?是否是畫蛇添足?在《Java并發(fā)編程實(shí)戰(zhàn)》一書中有詳細(xì)論述,簡(jiǎn)單的說(shuō),ConcurrentHashMap可以保證put或者remove方法一定是線程安全的,但它不能保證put、get、remove的組合操作是線程安全的,為了保證組合操作也是線程安全的,所以使用了lock。

com.github.pagehelper.PageHelper.java源碼。

// Mybatis攔截器方法 public Object intercept(Invocation invocation) throws Throwable { if (autoRuntimeDialect) { // 多數(shù)據(jù)源 SqlUtil sqlUtil = getSqlUtil(invocation); return sqlUtil.processPage(invocation); } else { // 單數(shù)據(jù)源 if (autoDialect) { initSqlUtil(invocation); } // 指定了dialect return sqlUtil.processPage(invocation); } } public synchronized void initSqlUtil(Invocation invocation) { if (this.sqlUtil == null) { this.sqlUtil = getSqlUtil(invocation); if (!autoRuntimeDialect) { properties = null; sqlUtilConfig = null; } autoDialect = false; } } public void setProperties(Properties p) { checkVersion(); //多數(shù)據(jù)源時(shí),獲取jdbcurl后是否關(guān)閉數(shù)據(jù)源 String closeConn = p.getProperty("closeConn"); //解決#97 if(StringUtil.isNotEmpty(closeConn)){ this.closeConn = Boolean.parseBoolean(closeConn); } //初始化SqlUtil的PARAMS SqlUtil.setParams(p.getProperty("params")); //數(shù)據(jù)庫(kù)方言 String dialect = p.getProperty("dialect"); String runtimeDialect = p.getProperty("autoRuntimeDialect"); if (StringUtil.isNotEmpty(runtimeDialect) && runtimeDialect.equalsIgnoreCase("TRUE")) { this.autoRuntimeDialect = true; this.autoDialect = false; this.properties = p; } else if (StringUtil.isEmpty(dialect)) { autoDialect = true; this.properties = p; } else { autoDialect = false; sqlUtil = new SqlUtil(dialect); sqlUtil.setProperties(p); } } public SqlUtil getSqlUtil(Invocation invocation) { MappedStatement ms = (MappedStatement) invocation.getArgs()[0]; //改為對(duì)dataSource做緩存 DataSource dataSource = ms.getConfiguration().getEnvironment().getDataSource(); String url = getUrl(dataSource); if (urlSqlUtilMap.containsKey(url)) { return urlSqlUtilMap.get(url); } try { lock.lock(); if (urlSqlUtilMap.containsKey(url)) { return urlSqlUtilMap.get(url); } if (StringUtil.isEmpty(url)) { throw new RuntimeException("無(wú)法自動(dòng)獲取jdbcUrl,請(qǐng)?jiān)诜猪?yè)插件中配置dialect參數(shù)!"); } String dialect = Dialect.fromJdbcUrl(url); if (dialect == null) { throw new RuntimeException("無(wú)法自動(dòng)獲取數(shù)據(jù)庫(kù)類型,請(qǐng)通過(guò)dialect參數(shù)指定!"); } SqlUtil sqlUtil = new SqlUtil(dialect); if (this.properties != null) { sqlUtil.setProperties(properties); } else if (this.sqlUtilConfig != null) { sqlUtil.setSqlUtilConfig(this.sqlUtilConfig); } urlSqlUtilMap.put(url, sqlUtil); return sqlUtil; } finally { lock.unlock(); } }

autoRuntimeDialect:多數(shù)據(jù)源,會(huì)創(chuàng)建多個(gè)SqlUtil。

autoDialect:單數(shù)據(jù)源,只會(huì)創(chuàng)建1個(gè)SqlUtil。單數(shù)據(jù)源時(shí),也可以當(dāng)做多數(shù)據(jù)源來(lái)使用。

指定了dialect:只會(huì)創(chuàng)建1個(gè)SqlUtil。

3.?PageSqlSource

public abstract class PageSqlSource implements SqlSource { /** * 獲取正常的BoundSql * * @param parameterObject * @return */ protected abstract BoundSql getDefaultBoundSql(Object parameterObject); /** * 獲取Count查詢的BoundSql * * @param parameterObject * @return */ protected abstract BoundSql getCountBoundSql(Object parameterObject); /** * 獲取分頁(yè)查詢的BoundSql * * @param parameterObject * @return */ protected abstract BoundSql getPageBoundSql(Object parameterObject); /** * 獲取BoundSql * * @param parameterObject * @return */ @Override public BoundSql getBoundSql(Object parameterObject) { Boolean count = getCount(); if (count == null) { return getDefaultBoundSql(parameterObject); } else if (count) { return getCountBoundSql(parameterObject); } else { return getPageBoundSql(parameterObject); } }}

getDefaultBoundSql:獲取原始的未經(jīng)改造的BoundSql。

getCountBoundSql:不需要寫count查詢,插件根據(jù)分頁(yè)查詢sql,智能的為你生成的count查詢BoundSql。

getPageBoundSql:獲取分頁(yè)查詢的BoundSql。

舉例:

DefaultBoundSql:select ?stud_id as studId , name, email, dob, phone from students

CountBoundSql:select ?count(0) from students --由PageHelper智能完成

PageBoundSql:select ?stud_id as studId , name, email, dob, phone from students limit ?, ?

(Made In Intellij Idea IDE)

public class PageStaticSqlSource extends PageSqlSource { private String sql; private List parameterMappings; private Configuration configuration; private SqlSource original; @Override protected BoundSql getDefaultBoundSql(Object parameterObject) { String tempSql = sql; String orderBy = PageHelper.getOrderBy(); if (orderBy != null) { tempSql = OrderByParser.converToOrderBySql(sql, orderBy); } return new BoundSql(configuration, tempSql, parameterMappings, parameterObject); } @Override protected BoundSql getCountBoundSql(Object parameterObject) { // localParser指的就是MysqlParser或者OracleParser // localParser.get().getCountSql(sql),可以根據(jù)原始的sql,生成一個(gè)count查詢的sql return new BoundSql(configuration, localParser.get().getCountSql(sql), parameterMappings, parameterObject); } @Override protected BoundSql getPageBoundSql(Object parameterObject) { String tempSql = sql; String orderBy = PageHelper.getOrderBy(); if (orderBy != null) { tempSql = OrderByParser.converToOrderBySql(sql, orderBy); } // getPageSql可以根據(jù)原始的sql,生成一個(gè)帶有分頁(yè)參數(shù)信息的sql,比如 limit ?, ? tempSql = localParser.get().getPageSql(tempSql); // 由于sql增加了分頁(yè)參數(shù)的?號(hào)占位符,getPageParameterMapping()就是在原有List基礎(chǔ)上,增加兩個(gè)分頁(yè)參數(shù)對(duì)應(yīng)的ParameterMapping對(duì)象,為分頁(yè)參數(shù)賦值使用 return new BoundSql(configuration, tempSql, localParser.get().getPageParameterMapping(configuration, original.getBoundSql(parameterObject)), parameterObject); }}

假設(shè)List原來(lái)的size=2,添加分頁(yè)參數(shù)后,其size=4,具體增加多少個(gè),看分頁(yè)參數(shù)的?號(hào)數(shù)量。

其他PageSqlSource,原理和PageStaticSqlSource一模一樣。

解析sql,并增加分頁(yè)參數(shù)占位符,或者生成count查詢的sql,都依靠Parser來(lái)完成。

4.?com.github.pagehelper.parser.Parser

(Made In Intellij Idea IDE)

public class MysqlParser extends AbstractParser { @Override public String getPageSql(String sql) { StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14); sqlBuilder.append(sql); sqlBuilder.append(" limit ?,?"); return sqlBuilder.toString(); } @Override public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page> page) { Map paramMap = super.setPageParameter(ms, parameterObject, boundSql, page); paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow()); paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize()); return paramMap; }}

我們可以清楚的看到,MysqlParser是如何添加分頁(yè)占位符和分頁(yè)參數(shù)的。

public abstract class AbstractParser implements Parser, Constant { public String getCountSql(final String sql) { return sqlParser.getSmartCountSql(sql); }}

生成count sql,則是前文提到的jsqlparser工具包來(lái)完成的,是另外一個(gè)開源的sql解析工具包。

5.?SqlUtil.doProcessPage()分頁(yè)查詢

// PageSqlSource裝飾原SqlSource public void processMappedStatement(MappedStatement ms) throws Throwable { SqlSource sqlSource = ms.getSqlSource(); MetaObject msObject = SystemMetaObject.forObject(ms); SqlSource pageSqlSource; if (sqlSource instanceof StaticSqlSource) { pageSqlSource = new PageStaticSqlSource((StaticSqlSource) sqlSource); } else if (sqlSource instanceof RawSqlSource) { pageSqlSource = new PageRawSqlSource((RawSqlSource) sqlSource); } else if (sqlSource instanceof ProviderSqlSource) { pageSqlSource = new PageProviderSqlSource((ProviderSqlSource) sqlSource); } else if (sqlSource instanceof DynamicSqlSource) { pageSqlSource = new PageDynamicSqlSource((DynamicSqlSource) sqlSource); } else { throw new RuntimeException("無(wú)法處理該類型[" + sqlSource.getClass() + "]的SqlSource"); } msObject.setValue("sqlSource", pageSqlSource); //由于count查詢需要修改返回值,因此這里要?jiǎng)?chuàng)建一個(gè)Count查詢的MS msCountMap.put(ms.getId(), MSUtils.newCountMappedStatement(ms)); }// 執(zhí)行分頁(yè)查詢private Page doProcessPage(Invocation invocation, Page page, Object[] args) throws Throwable { //保存RowBounds狀態(tài) RowBounds rowBounds = (RowBounds) args[2]; //獲取原始的ms MappedStatement ms = (MappedStatement) args[0]; //判斷并處理為PageSqlSource if (!isPageSqlSource(ms)) { processMappedStatement(ms); } //設(shè)置當(dāng)前的parser,后面每次使用前都會(huì)set,ThreadLocal的值不會(huì)產(chǎn)生不良影響 ((PageSqlSource)ms.getSqlSource()).setParser(parser); try { //忽略RowBounds-否則會(huì)進(jìn)行Mybatis自帶的內(nèi)存分頁(yè) args[2] = RowBounds.DEFAULT; //如果只進(jìn)行排序 或 pageSizeZero的判斷 if (isQueryOnly(page)) { return doQueryOnly(page, invocation); } //簡(jiǎn)單的通過(guò)total的值來(lái)判斷是否進(jìn)行count查詢 if (page.isCount()) { page.setCountSignal(Boolean.TRUE); //替換MS args[0] = msCountMap.get(ms.getId()); //查詢總數(shù) Object result = invocation.proceed(); //還原ms args[0] = ms; //設(shè)置總數(shù) page.setTotal((Integer) ((List) result).get(0)); if (page.getTotal() == 0) { return page; } } else { page.setTotal(-1l); } //pageSize>0的時(shí)候執(zhí)行分頁(yè)查詢,pageSize<=0的時(shí)候不執(zhí)行相當(dāng)于可能只返回了一個(gè)count if (page.getPageSize() > 0 && ((rowBounds == RowBounds.DEFAULT && page.getPageNum() > 0) || rowBounds != RowBounds.DEFAULT)) { //將參數(shù)中的MappedStatement替換為新的qs page.setCountSignal(null); BoundSql boundSql = ms.getBoundSql(args[1]); args[1] = parser.setPageParameter(ms, args[1], boundSql, page); page.setCountSignal(Boolean.FALSE); //執(zhí)行分頁(yè)查詢 Object result = invocation.proceed(); //得到處理結(jié)果 page.addAll((List) result); } } finally { ((PageSqlSource)ms.getSqlSource()).removeParser(); } //返回結(jié)果 return page; }

源碼中注意關(guān)鍵的四點(diǎn)即可:

1、msCountMap.put(ms.getId(), MSUtils.newCountMappedStatement(ms)),創(chuàng)建count查詢的MappedStatement對(duì)象,并緩存于msCountMap。

2、如果count=true,則執(zhí)行count查詢,結(jié)果total值保存于page對(duì)象中,繼續(xù)執(zhí)行分頁(yè)查詢。

3、執(zhí)行分頁(yè)查詢,將查詢結(jié)果保存于page對(duì)象中,page是一個(gè)ArrayList對(duì)象。

4、
args[2] = RowBounds.DEFAULT,改變Mybatis原有分頁(yè)行為;

args[1] = parser.setPageParameter(ms, args[1], boundSql, page),改變?cè)袇?shù)列表(增加分頁(yè)參數(shù))。

6.?PageHelper的兩種使用方式

第一種、直接通過(guò)RowBounds參數(shù)完成分頁(yè)查詢 。

List list = studentMapper.find(new RowBounds(0, 10));Page page = ((Page) list;

第二種、PageHelper.startPage()靜態(tài)方法

//獲取第1頁(yè),10條內(nèi)容,默認(rèn)查詢總數(shù)count PageHelper.startPage(1, 10);//緊跟著的第一個(gè)select方法會(huì)被分頁(yè) List list = studentMapper.find(); Page page = ((Page) list;

注:返回結(jié)果list,已經(jīng)是Page對(duì)象,Page對(duì)象是一個(gè)ArrayList。

原理:使用ThreadLocal來(lái)傳遞和保存Page對(duì)象,每次查詢,都需要單獨(dú)設(shè)置PageHelper.startPage()方法。

public class SqlUtil implements Constant { private static final ThreadLocal LOCAL_PAGE = new ThreadLocal();}

本文中經(jīng)常提到的count查詢,其實(shí)是PageHelper幫助我們生成的一個(gè)MappedStatement內(nèi)存對(duì)象,它可以免去我們?cè)赬XXMapper.xml內(nèi)單獨(dú)聲明一個(gè)sql count查詢,我們只需要寫一個(gè)sql分頁(yè)業(yè)務(wù)查詢即可。

PageHelper使用建議(性能最好):

  • 明確指定dialect。

  • 明確編寫sql分頁(yè)業(yè)務(wù)和與它對(duì)應(yīng)的count查詢,別圖省事。

總結(jié)

以上是生活随笔為你收集整理的mybatis 分页需要的jar包下载_牛逼哄哄的PageHelper分页插件到底牛在哪里?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。