1. 程式人生 > >Mybatis分頁-利用Mybatis Generator外掛生成基於資料庫方言的分頁語句,統計記錄總數

Mybatis分頁-利用Mybatis Generator外掛生成基於資料庫方言的分頁語句,統計記錄總數

眾所周知,Mybatis本身沒有提供基於資料庫方言的分頁功能,而是基於JDBC的遊標分頁,很容易出現效能問題。網上有很多分頁的解決方案,不外乎是基於Mybatis本機的外掛機制,通過攔截Sql做分頁。但是在像Oracle這樣的資料庫上,攔截器生成的Sql語句沒有變數繫結,而且每次語句的都要去攔截,感覺有點浪費效能。

Mybatis Generator是Mybatis的程式碼生成工具,可以生成大部分的查詢語句。

本文提供的分頁解決方案是新增Mybatis Generator外掛,在用Mybatis Generator生成Mybatis程式碼時,直接生成基於資料庫方言的Sql語句,解決Oralce等資料庫的變數繫結,且無需使用Mybatis攔截器去攔截語句判斷分頁。

一、編寫Mybatis Generator Dialect外掛

/**

Java程式碼  收藏程式碼
  1.  * Copyright (C) 2011 Tgwoo Inc.  
  2.  * http://www.tgwoo.com/  
  3.  */  
  4. package com.tgwoo.core.dao.plugin;  
  5. import java.util.List;  
  6. import org.mybatis.generator.api.CommentGenerator;  
  7. import org.mybatis.generator.api.IntrospectedTable;  
  8. import org.mybatis.generator.api.PluginAdapter;  
  9. import org.mybatis.generator.api.dom.java.Field;  
  10. import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;  
  11. import org.mybatis.generator.api.dom.java.JavaVisibility;  
  12. import org.mybatis.generator.api.dom.java.Method;  
  13. import org.mybatis.generator.api.dom.java.Parameter;  
  14. import org.mybatis.generator.api.dom.java.TopLevelClass;  
  15. import org.mybatis.generator.api.dom.xml.Attribute;  
  16. import org.mybatis.generator.api.dom.xml.Document;  
  17. import org.mybatis.generator.api.dom.xml.TextElement;  
  18. import org.mybatis.generator.api.dom.xml.XmlElement;  
  19. /** 
  20.  * @author pan.wei 
  21.  * @date 2011-11-30 下午08:36:11 
  22.  */  
  23. public class OraclePaginationPlugin extends PluginAdapter {  
  24.     @Override  
  25.     public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,  
  26.             IntrospectedTable introspectedTable) {  
  27.         // add field, getter, setter for limit clause  
  28.         addPage(topLevelClass, introspectedTable, "page");  
  29.         return super.modelExampleClassGenerated(topLevelClass,  
  30.                 introspectedTable);  
  31.     }  
  32.     @Override  
  33.     public boolean sqlMapDocumentGenerated(Document document,  
  34.             IntrospectedTable introspectedTable) {  
  35.         XmlElement parentElement = document.getRootElement();  
  36.         // 產生分頁語句前半部分  
  37.         XmlElement paginationPrefixElement = new XmlElement("sql");  
  38.         paginationPrefixElement.addAttribute(new Attribute("id",  
  39.                 "OracleDialectPrefix"));  
  40.         XmlElement pageStart = new XmlElement("if");  
  41.         pageStart.addAttribute(new Attribute("test""page != null"));  
  42.         pageStart.addElement(new TextElement(  
  43.                 "select * from ( select row_.*, rownum rownum_ from ( "));  
  44.         paginationPrefixElement.addElement(pageStart);  
  45.         parentElement.addElement(paginationPrefixElement);  
  46.         // 產生分頁語句後半部分  
  47.         XmlElement paginationSuffixElement = new XmlElement("sql");  
  48.         paginationSuffixElement.addAttribute(new Attribute("id",  
  49.                 "OracleDialectSuffix"));  
  50.         XmlElement pageEnd = new XmlElement("if");  
  51.         pageEnd.addAttribute(new Attribute("test""page != null"));  
  52.         pageEnd.addElement(new TextElement(  
  53.                 "<![CDATA[ ) row_ ) where rownum_ > #{page.begin} and rownum_ <= #{page.end} ]]>"));  
  54.         paginationSuffixElement.addElement(pageEnd);  
  55.         parentElement.addElement(paginationSuffixElement);  
  56.         return super.sqlMapDocumentGenerated(document, introspectedTable);  
  57.     }  
  58.     @Override  
  59.     public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(  
  60.             XmlElement element, IntrospectedTable introspectedTable) {  
  61.         XmlElement pageStart = new XmlElement("include"); //$NON-NLS-1$     
  62.         pageStart.addAttribute(new Attribute("refid""OracleDialectPrefix"));  
  63.         element.getElements().add(0, pageStart);  
  64.         XmlElement isNotNullElement = new XmlElement("include"); //$NON-NLS-1$     
  65.         isNotNullElement.addAttribute(new Attribute("refid",  
  66.                 "OracleDialectSuffix"));  
  67.         element.getElements().add(isNotNullElement);  
  68.         return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element,  
  69.                 introspectedTable);  
  70.     }  
  71.     /** 
  72.      * @param topLevelClass 
  73.      * @param introspectedTable 
  74.      * @param name 
  75.      */  
  76.     private void addPage(TopLevelClass topLevelClass,  
  77.             IntrospectedTable introspectedTable, String name) {  
  78.         topLevelClass.addImportedType(new FullyQualifiedJavaType(  
  79.                 "com.tgwoo.core.dao.pojo.Page"));  
  80.         CommentGenerator commentGenerator = context.getCommentGenerator();  
  81.         Field field = new Field();  
  82.         field.setVisibility(JavaVisibility.PROTECTED);  
  83.         field.setType(new FullyQualifiedJavaType("com.tgwoo.core.dao.pojo.Page"));  
  84.         field.setName(name);  
  85.         commentGenerator.addFieldComment(field, introspectedTable);  
  86.         topLevelClass.addField(field);  
  87.         char c = name.charAt(0);  
  88.         String camel = Character.toUpperCase(c) + name.substring(1);  
  89.         Method method = new Method();  
  90.         method.setVisibility(JavaVisibility.PUBLIC);  
  91.         method.setName("set" + camel);  
  92.         method.addParameter(new Parameter(new FullyQualifiedJavaType(  
  93.                 "com.tgwoo.core.dao.pojo.Page"), name));  
  94.         method.addBodyLine("this." + name + "=" + name + ";");  
  95.         commentGenerator.addGeneralMethodComment(method, introspectedTable);  
  96.         topLevelClass.addMethod(method);  
  97.         method = new Method();  
  98.         method.setVisibility(JavaVisibility.PUBLIC);  
  99.         method.setReturnType(new FullyQualifiedJavaType(  
  100.                 "com.tgwoo.core.dao.pojo.Page"));  
  101.         method.setName("get" + camel);  
  102.         method.addBodyLine("return " + name + ";");  
  103.         commentGenerator.addGeneralMethodComment(method, introspectedTable);  
  104.         topLevelClass.addMethod(method);  
  105.     }  
  106.     /** 
  107.      * This plugin is always valid - no properties are required 
  108.      */  
  109.     public boolean validate(List<String> warnings) {  
  110.         return true;  
  111.     }  
  112. }  

二、增加外掛到Mybatis Generator配置檔案中

<?xml version="1.0" encoding="UTF-8" ?>

Xml程式碼  收藏程式碼
  1. <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >  
  2. <generatorConfiguration >  
  3.     <classPathEntry location="E:\work\eclipseWorkspace\myEclipse\CTSPMTS\WebRoot\WEB-INF\lib\ojdbc14.jar" />  
  4.     <context id="oracle" >  
  5.         <plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin"></plugin>  
  6.         <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>  
  7.         <!-- Pagination -->  
  8.         <plugin type="com.tgwoo.core.dao.plugin.OraclePaginationPlugin"></plugin>  
  9.         <commentGenerator>    
  10.            <property name="suppressDate" value="true" />    
  11.             <property name="suppressAllComments" value="true" />  
  12.         </commentGenerator>    
  13.         <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@192.168.0.2:1521:ctspmt" userId="ctspmt" password="ctspmt123" />  
  14.         <javaModelGenerator targetPackage="com.tgwoo.ctspmt.model" targetProject="CTSPMTS/src" />  
  15.         <sqlMapGenerator targetPackage="com.tgwoo.ctspmt.data" targetProject="CTSPMTS/src" />  
  16.         <javaClientGenerator targetPackage="com.tgwoo.ctspmt.data" targetProject="CTSPMTS/src" type="XMLMAPPER" /><!-- 
  17.         <table schema="ctspmt" tableName="mt_e_interface_log"/> 
  18.         --><!--  
  19.         <table schema="ctspmt" tableName="mt_e_msg" />  
  20.         <table schema="ctspmt" tableName="mt_e_msg_log" />  
  21.         <table schema="ctspmt" tableName="mt_e_msg_receiver" />  
  22.         <table schema="ctspmt" tableName="st_e_org" />  
  23.         <table schema="ctspmt" tableName="st_e_role" />  
  24.         <table schema="ctspmt" tableName="st_e_user" />  
  25.         <table schema="ctspmt" tableName="mt_e_user_msg_conf" />  
  26. 相關推薦

    Mybatis-利用Mybatis Generator外掛生成基於資料庫方言語句統計記錄總數

    眾所周知,Mybatis本身沒有提供基於資料庫方言的分頁功能,而是基於JDBC的遊標分頁,很容易出現效能問題。網上有很多分頁的解決方案,不外乎是基於Mybatis本機的外掛機制,通過攔截Sql做分頁。但是在像Oracle這樣的資料庫上,攔截器生成的Sql語句沒有變數繫

    利用mybatis generator外掛生成基於語句解決方案

    1》 雖然MyBatis_Generator可以將常用的DAO中的方法都生成,但是唯獨忽視了一點——分頁,雖然MyBatis支援分頁,但是那個分頁是記憶體分頁,如果資料量大的話記憶體恐怕要承受不了,於是就自動動手改造自動化工具生成的程式碼使其支援真分頁. 本文裡面我說的是

    Mybatis3, 基於Mybatis Generator外掛生成語句

        Mybatis Generator外掛物理分頁,適用於targetRuntime="MyBatis3" package com.fxhx.gamelog.common.plugin; import java.util.List; import org.myb

    Mybatis3, 基於Mybatis Generator外掛生成MYSQL語句

    http://ibatis.apache.org/docs/tools/ibator/reference/pluggingIn.html Mybatis Generator外掛物理分頁,適用於targetRuntime="MyBatis3" package com

    SpringBoot---整合mybatis+generator自動生成程式碼+連線池+

    如何整合Springboot和Mybatis框架,然後使用generator自動生成mapper,pojo等檔案。然後再使用阿里巴巴提供的開源連線池druid,這個連線池的好處我就不說了,集合了所有連線池的好處,並且還提供了監控等功能,加大了可擴充套件性等等。 idea 新建sp

    eclipse 使用 mybatis generator 外掛生成 MyBatis 逆向工程

    步驟: 1.新建Java工程,新增config包 2.在config包中新增generratorConfigure檔案 3.在config包中新建properties包,並新增properties檔案 完成後的目錄: 配置檔案的的程式碼: generat

    通過idea-mybatis-generator外掛生成實體和mapper

    通過idea-mybatis-generator外掛生成實體和mapper 外掛安裝 首先開啟外掛市場 搜尋idea-mybatis-generator外掛 外掛使用 開啟外掛 配置

    IntelliJ Idea使用筆記1.使用mybatis generator外掛生成程式碼。

    使用generator 生成程式碼的方式很多,我這用的是在idea裡maven外掛方式。 1.在pom.xml檔案中新增mybatis外掛,在plugins節點下新增 <plugin> <groupId>org.mybatis.generator</grou

    資料庫分庫表(sharding)系列(三) 關於使用框架還是自主開發以及sharding實現層面的考量 資料庫分庫表(sharding)系列(二) 全域性主鍵生成策略 資料庫分庫表(sharding)系列(一) 拆分實施策略和示例演示

    分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

    布式事務、多數據源、分庫表中間件之spring boot基於Atomikos+XADataSource布式事務配置(100%純動態)

    ads list() row safe ilo list odin context factor 本文描述spring boot基於Atomikos+DruidXADataSource分布式事務配置(100%純動態),也就是增加、減少數據源只需要修改application.

    Markdown For EditPlus外掛釋出(基於EditPlus快速編輯Markdonw檔案寫作愛好的福音來啦)

    詳細介紹: Markdown For EditPlus外掛使用說明 開發緣由 特點好處: 中文版使用說明 相關命令(輸入字元敲空格自動輸出): EditPlus常用快捷鍵: 相關教程: English description Command(Enter command

    SpringBoot入門篇--整合mybatis+generator自動生成程式碼+druid連線池+PageHelper外掛

    我們這一一篇部落格講的是如何整合Springboot和Mybatis框架,然後使用generator自動生成mapper,pojo等檔案。然後再使用阿里巴巴提供的開源連線池druid,這個連線池的好處我就不說了,集合了所有連線池的好處,並且還提供了監控等功能,加大了可擴充套件性等等。   1.&

    mybatis generator外掛系列--外掛

    1、首先定義分頁外掛 MysqlPagePlugin.java package com.demo.mybatis.plugin; import org.mybatis.generator.api.CommentGenerator; import org.mybati

    springboot2.0.5整合mybatis(PageHelper外掛generator外掛使用)

    用IDEA搭建springboot2.0.5專案 選擇Spring initializr就可以輕鬆搭建一個springboot專案,第一次搭建很費時 在Group寫上公司域名,Artifact寫上專案名,打包用Jar 選Web勾選 SQL項,勾選MySQL

    Mybatis-Plus來學習一下!程式碼生成外掛

    在這裡小小推薦下我的個人部落格 簡書:雷園的簡書 今天我們來說一下Mybatis-Plus! 個人認為呢,Mybatis-Plus是Mybatis的增強版,他只是在Mybatis的基礎上增加了功能,且並未對原有功能進行任何的改動。可謂是非常良心的一款開源

    mybatis generator生成帶有Mybatis程式碼

    MyBatis開發,最讓人開心的就是可以隨意寫SQL,這樣有多好的效能的SQL都可以進行調優。 但是MyBatis的優點也是它的缺點,不論什麼專案都需要編寫SQL,令人頭疼的要命,一般業務(例如單表操作)的簡單查詢、修改、刪除、插入,都需要自己手工去編寫SQL。 還好有第

    擴充套件mybatis-generator外掛;高效率查詢,自動新增swagger2註解到實體類

    myBatisGeneratorPlugins 一些mybatis-generator擴充套件外掛集合 已實現功能 自動新增swagger2註解到實體類 擴充套件set方法,返回this例項;方便鏈式呼叫 詳細介紹 1. 自動新增swagger2註解到實體類 自動

    springboot整合mybatisgenerator自動生成程式碼)

    generator自動生成程式碼 1:匯入外掛 <!-- mybatis generator 自動生成程式碼外掛 --> <plugin> <groupId>org.mybatis.generator</groupI

    MyBatis(七)——使用PageHelper外掛進行

    一、概述   PageHelper是MyBatis中非常方便的第三方分頁外掛。      官方文件: https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md   Ho

    MybatisPagehelper以及前端外掛結合使用完整版

    前端效果圖: 後臺部分 maven依賴: 基於mybatis <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-