zoukankan      html  css  js  c++  java
  • Mybatis Generator实现分页功能

     

    Mybatis Generator实现分页功能

    分类: IBATIS 882人阅读 评论(1) 收藏 举报
    众所周知,Mybatis本身没有提供基于数据库方言的分页功能,而是基于JDBC的游标分页,很容易出现性能问题。网上有很多分页的解决方案,不外乎是基于Mybatis本机的插件机制,通过拦截Sql做分页。但是在像Oracle这样的数据库上,拦截器生成的Sql语句没有变量绑定,而且每次语句的都要去拦截,感觉有点浪费性能。

    Mybatis Generator是Mybatis的代码生成工具,可以生成大部分的查询语句。

    本文提供的分页解决方案是新增Mybatis Generator插件,在用Mybatis Generator生成Mybatis代码时,直接生成基于数据库方言的Sql语句,解决Oralce等数据库的变量绑定,且无需使用Mybatis拦截器去拦截语句判断分页。

    一、编写Mybatis Generator Dialect插件

    /**

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

    二、增加插件到Mybatis Generator配置文件中

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

    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:workeclipseWorkspacemyEclipseCTSPMTSWebRootWEB-INFlibojdbc14.jar" />  
    4.       
    5.     <context id="oracle" >  
    6.         <plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin"></plugin>  
    7.         <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>  
    8.         <!-- Pagination -->  
    9.         <plugin type="com.tgwoo.core.dao.plugin.OraclePaginationPlugin"></plugin>  
    10.           
    11.         <commentGenerator>    
    12.            <property name="suppressDate" value="true" />    
    13.             <property name="suppressAllComments" value="true" />  
    14.         </commentGenerator>    
    15.           
    16.         <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@192.168.0.2:1521:ctspmt" userId="ctspmt" password="ctspmt123" />  
    17.         <javaModelGenerator targetPackage="com.tgwoo.ctspmt.model" targetProject="CTSPMTS/src" />  
    18.         <sqlMapGenerator targetPackage="com.tgwoo.ctspmt.data" targetProject="CTSPMTS/src" />  
    19.         <javaClientGenerator targetPackage="com.tgwoo.ctspmt.data" targetProject="CTSPMTS/src" type="XMLMAPPER" /><!-- 
    20.        
    21.         <table schema="ctspmt" tableName="mt_e_interface_log"/> 
    22.         --><!--  
    23.         <table schema="ctspmt" tableName="mt_e_msg" />  
    24.         <table schema="ctspmt" tableName="mt_e_msg_log" />  
    25.         <table schema="ctspmt" tableName="mt_e_msg_receiver" />  
    26.         <table schema="ctspmt" tableName="st_e_org" />  
    27.         <table schema="ctspmt" tableName="st_e_role" />  
    28.         <table schema="ctspmt" tableName="st_e_user" />  
    29.         <table schema="ctspmt" tableName="mt_e_user_msg_conf" />  
    30.         <table schema="ctspmt" tableName="mt_j_user_device" />  
    31.         <table schema="ctspmt" tableName="st_j_user_role" />  
    32.         <table schema="ctspmt" tableName="ST_E_UNIQUE_KEY" />       
    33.         --><table schema="ctspmt" tableName="mt_v_msg_item" />  
    34.      </context>  
    35.        
    36. </generatorConfiguration>  

    三、示例

    /**

    1.  * Copyright (C) 2011 Tgwoo Inc.  
    2.  * http://www.tgwoo.com/  
    3.  */  
    4. package com.tgwoo.ctspmt.test;  
    5.   
    6. import com.tgwoo.core.config.SpringBeanProxy;  
    7. import com.tgwoo.core.dao.pojo.Page;  
    8. import com.tgwoo.ctspmt.data.MtVMsgItemMapper;  
    9. import com.tgwoo.ctspmt.model.MtVMsgItemExample;  
    10.   
    11. /** 
    12.  * @author pan.wei 
    13.  * @date 2011-11-25 下午01:26:17 
    14.  */  
    15. public class Test {  
    16.     /** 
    17.      * @param args 
    18.      */  
    19.     public static void main(String[] args) {  
    20.         //get spring mapper instance   
    21.         MtVMsgItemMapper mapper = SpringBeanProxy.getCtx().getBean(  
    22.                 MtVMsgItemMapper.class);  
    23.         MtVMsgItemExample ex = new MtVMsgItemExample();  
    24.         Page page = new Page(010);  
    25.         ex.setPage(page);  
    26.         ex.createCriteria().andMsgCodeEqualTo("222");  
    27.         // set count,up to you  
    28.         page.setCount(mapper.countByExample(ex));  
    29.         int row = mapper.selectByExample(ex).size();  
    30.         System.out.println("============row:" + row + "================");  
    31.     }  
    32.   
    33. }  

    四、分页类

    1. package com.tgwoo.core.dao.pojo;  
    2.   
    3. /** 
    4.  * @author pan.wei 
    5.  * @date 2011-12-1 上午11:36:12 
    6.  */  
    7. public class Page {  
    8.     // 分页查询开始记录位置  
    9.     private int begin;  
    10.     // 分页查看下结束位置  
    11.     private int end;  
    12.     // 每页显示记录数  
    13.     private int length;  
    14.     // 查询结果总记录数  
    15.     private int count;  
    16.     // 当前页码  
    17.     private int current;  
    18.     // 总共页数  
    19.     private int total;  
    20.   
    21.     public Page() {  
    22.     }  
    23.   
    24.     /** 
    25.      * 构造函数 
    26.      *  
    27.      * @param begin 
    28.      * @param length 
    29.      */  
    30.     public Page(int begin, int length) {  
    31.         this.begin = begin;  
    32.         this.length = length;  
    33.         this.end = this.begin + this.length;  
    34.         this.current = (int) Math.floor((this.begin * 1.0d) / this.length) + 1;  
    35.     }  
    36.   
    37.     /** 
    38.      * @param begin 
    39.      * @param length 
    40.      * @param count 
    41.      */  
    42.     public Page(int begin, int length, int count) {  
    43.         this(begin, length);  
    44.         this.count = count;  
    45.     }  
    46.   
    47.     /** 
    48.      * @return the begin 
    49.      */  
    50.     public int getBegin() {  
    51.         return begin;  
    52.     }  
    53.   
    54.     /** 
    55.      * @return the end 
    56.      */  
    57.     public int getEnd() {  
    58.         return end;  
    59.     }  
    60.   
    61.     /** 
    62.      * @param end 
    63.      *            the end to set 
    64.      */  
    65.     public void setEnd(int end) {  
    66.         this.end = end;  
    67.     }  
    68.   
    69.     /** 
    70.      * @param begin 
    71.      *            the begin to set 
    72.      */  
    73.     public void setBegin(int begin) {  
    74.         this.begin = begin;  
    75.         if (this.length != 0) {  
    76.             this.current = (int) Math.floor((this.begin * 1.0d) / this.length) + 1;  
    77.         }  
    78.     }  
    79.   
    80.     /** 
    81.      * @return the length 
    82.      */  
    83.     public int getLength() {  
    84.         return length;  
    85.     }  
    86.   
    87.     /** 
    88.      * @param length 
    89.      *            the length to set 
    90.      */  
    91.     public void setLength(int length) {  
    92.         this.length = length;  
    93.         if (this.begin != 0) {  
    94.             this.current = (int) Math.floor((this.begin * 1.0d) / this.length) + 1;  
    95.         }  
    96.     }  
    97.   
    98.     /** 
    99.      * @return the count 
    100.      */  
    101.     public int getCount() {  
    102.         return count;  
    103.     }  
    104.   
    105.     /** 
    106.      * @param count 
    107.      *            the count to set 
    108.      */  
    109.     public void setCount(int count) {  
    110.         this.count = count;  
    111.         this.total = (int) Math.floor((this.count * 1.0d) / this.length);  
    112.         if (this.count % this.length != 0) {  
    113.             this.total++;  
    114.         }  
    115.     }  
    116.   
    117.     /** 
    118.      * @return the current 
    119.      */  
    120.     public int getCurrent() {  
    121.         return current;  
    122.     }  
    123.   
    124.     /** 
    125.      * @param current 
    126.      *            the current to set 
    127.      */  
    128.     public void setCurrent(int current) {  
    129.         this.current = current;  
    130.     }  
    131.   
    132.     /** 
    133.      * @return the total 
    134.      */  
    135.     public int getTotal() {  
    136.         if (total == 0) {  
    137.             return 1;  
    138.         }  
    139.         return total;  
    140.     }  
    141.   
    142.     /** 
    143.      * @param total 
    144.      *            the total to set 
    145.      */  
    146.     public void setTotal(int total) {  
    147.         this.total = total;  
    148.     }  
    149.   
    150. }  

    五、生成后的代码

    1、Example代码

    1. package com.tgwoo.ctspmt.model;  
    2.   
    3. import com.tgwoo.core.dao.pojo.Page;  
    4. import java.math.BigDecimal;  
    5. import java.util.ArrayList;  
    6. import java.util.Date;  
    7. import java.util.Iterator;  
    8. import java.util.List;  
    9.   
    10. public class MtVMsgItemExample {  
    11.     protected String orderByClause;  
    12.   
    13.     protected boolean distinct;  
    14.   
    15.     protected List<Criteria> oredCriteria;  
    16.   
    17.     protected Page page;  
    18.      
    19.     ...  

    2、mapper.xml

    1. ...  
    2.  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.tgwoo.ctspmt.model.MtVMsgItemExample" >  
    3.     <include refid="OracleDialectPrefix" />  
    4.     select  
    5.     <if test="distinct" >  
    6.       distinct  
    7.     </if>  
    8.     <include refid="Base_Column_List" />  
    9.     from CTSPMT.MT_V_MSG_ITEM  
    10.     <if test="_parameter != null" >  
    11.       <include refid="Example_Where_Clause" />  
    12.     </if>  
    13.     <if test="orderByClause != null" >  
    14.       order by ${orderByClause}  
    15.     </if>  
    16.     <include refid="OracleDialectSuffix" />  
    17.   </select>  
    18. ...  
    19.   <sql id="OracleDialectPrefix" >  
    20.     <if test="page != null" >  
    21.       select * from ( select row_.*, rownum rownum_ from (   
    22.     </if>  
    23.   </sql>  
    24.   <sql id="OracleDialectSuffix" >  
    25.     <if test="page != null" >  
    26.       <![CDATA[ ) row_ ) where rownum_ > #{page.begin} and rownum_ <= #{page.end} ]]>  
    27.     </if>  
    28.   </sql>  
    29. ...  

    附件是Mybatis Generatorjar包。

    其他数据库的方言可以按照Oracle的去改写,有写好的希望能共享下。

    -------------------------------------------------------------------------------------------------------

    maven管理:

    1、pom.xml

    1. <build>  
    2.         <plugins>  
    3.             <plugin>  
    4.                 <groupId>org.mybatis.generator</groupId>  
    5.                 <artifactId>mybatis-generator-maven-plugin</artifactId>  
    6.                 <version>1.3.1</version>  
    7.                 <executions>  
    8.                     <execution>  
    9.                         <id>Generate MyBatis Artifacts</id>  
    10.                         <goals>  
    11.                             <goal>generate</goal>  
    12.                         </goals>  
    13.                     </execution>  
    14.                 </executions>  
    15.                 <dependencies>  
    16.                     <dependency>  
    17.                         <groupId>com.oracle</groupId>  
    18.                         <artifactId>ojdbc14</artifactId>  
    19.                         <version>10.2.0.4.0</version>  
    20.                     </dependency>  
    21.                 </dependencies>  
    22.             </plugin>  
    23.         </plugins>  
    24.     </build>  

    2、generatorConfig.xml

    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <!DOCTYPE generatorConfiguration  
    3.   PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"  
    4.   "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">  
    5. <generatorConfiguration>  
    6.     <context id="oracleGenerator" targetRuntime="MyBatis3">  
    7.         <plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin"></plugin>  
    8.         <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>  
    9.         <!-- Pagination -->  
    10.         <plugin  
    11.             type="com.tgwoo.test.core.dao.mybatis.generator.plugin.pagination.OraclePaginationPlugin"></plugin>  
    12.   
    13.         <!-- 取消注释 -->  
    14.         <commentGenerator>  
    15.             <property name="suppressDate" value="true" />  
    16.             <property name="suppressAllComments" value="true" />  
    17.         </commentGenerator>  
    18.         <!-- 配置连接数据信息 -->  
    19.         <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"  
    20.             connectionURL="jdbc:oracle:thin:@192.168.0.2:1521:test" userId="test"  
    21.             password="test123" />  
    22.         <javaTypeResolver>  
    23.             <property name="forceBigDecimals" value="false" />  
    24.         </javaTypeResolver>  
    25.   
    26.         <!-- 配置自动生成的Model的保存路径与其它参数 -->  
    27.         <javaModelGenerator targetPackage="com.tgwoo.test.dao.model"  
    28.             targetProject=".srcmainjava">  
    29.             <property name="enableSubPackages" value="false" />  
    30.             <property name="trimStrings" value="true" />  
    31.         </javaModelGenerator>  
    32.   
    33.         <!-- 配置自动生成的Mappper.xml映射的保存路径与其它参数 -->  
    34.         <sqlMapGenerator targetPackage="com.tgwoo.test.dao"  
    35.             targetProject=".srcmain esources">  
    36.             <property name="enableSubPackages" value="false" />  
    37.         </sqlMapGenerator>  
    38.   
    39.         <!-- 配置自动生成的Mappper.java接口的保存路径与其它参数 -->  
    40.         <javaClientGenerator type="XMLMAPPER"  
    41.             targetPackage="com.tgwoo.test.dao" targetProject=".srcmainjava">  
    42.             <property name="enableSubPackages" value="false" />  
    43.         </javaClientGenerator>  
    44.   
    45.         <!-- 生成表对应的操作与实体对象 -->  
    46.         <table schema="test" tableName="testTable">  
    47.             <columnOverride column="id" javaType="Long" />  
    48.         </table>  
    49.     </context>  
    50. </generatorConfiguration>  

    3、run

    Goals:mybatis-generator:generate

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    1. package org.leef.db.mybatis.plugin;  
    2.   
    3. import java.util.List;  
    4.   
    5. import org.mybatis.generator.api.CommentGenerator;  
    6. import org.mybatis.generator.api.IntrospectedTable;  
    7. import org.mybatis.generator.api.PluginAdapter;  
    8. import org.mybatis.generator.api.ShellRunner;  
    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. /** 
    21.  * @author pan.wei 
    22.  * @date 2011-11-30 下午08:36:11 
    23.  */  
    24. public class OraclePaginationPlugin extends PluginAdapter {  
    25.   
    26.     @Override  
    27.     public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,  
    28.             IntrospectedTable introspectedTable) {  
    29.         // add field, getter, setter for limit clause  
    30.         addPage(topLevelClass, introspectedTable, "page");  
    31.         addDialect(topLevelClass, introspectedTable, "dialect");  
    32.         return super.modelExampleClassGenerated(topLevelClass,  
    33.                 introspectedTable);  
    34.     }  
    35.   
    36.     @Override  
    37.     public boolean sqlMapDocumentGenerated(Document document,  
    38.             IntrospectedTable introspectedTable) {  
    39.         XmlElement parentElement = document.getRootElement();  
    40.   
    41.         // 产生分页语句前半部分  
    42.         XmlElement paginationPrefixElement = new XmlElement("sql");  
    43.         paginationPrefixElement.addAttribute(new Attribute("id",  
    44.                 "OracleDialectPrefix"));  
    45.         XmlElement pageStart = new XmlElement("if");  
    46.         pageStart.addAttribute(new Attribute("test""page != null"));  
    47.         XmlElement pageDialect1 = new XmlElement("if");  
    48.         pageDialect1.addAttribute(new Attribute("test""dialect == 'oralce'"));  
    49.         pageStart.addElement(pageDialect1);  
    50.         pageDialect1.addElement(new TextElement(  
    51.                 "select * from ( select row_.*, rownum rownum_ from ( "));  
    52.         paginationPrefixElement.addElement(pageStart);  
    53.         parentElement.addElement(paginationPrefixElement);  
    54.   
    55.         // 产生分页语句后半部分  
    56.         XmlElement paginationSuffixElement = new XmlElement("sql");  
    57.         paginationSuffixElement.addAttribute(new Attribute("id",  
    58.                 "OracleDialectSuffix"));  
    59.         XmlElement pageEnd = new XmlElement("if");  
    60.         pageEnd.addAttribute(new Attribute("test""page != null"));  
    61.         XmlElement pageDialect2 = new XmlElement("if");  
    62.         pageDialect2.addAttribute(new Attribute("test""dialect == 'oralce'"));  
    63.         pageEnd.addElement(pageDialect2);  
    64.         pageDialect2.addElement(new TextElement(  
    65.                 "<![CDATA[ ) row_ ) where rownum_ > #{page.begin} and rownum_ <= #{page.end} ]]>"));  
    66.           
    67.         //----- mysql语句。  
    68.         XmlElement mysqlDialect = new XmlElement("if");  
    69.         mysqlDialect.addAttribute(new Attribute("test""dialect == 'mysql'"));  
    70.         pageEnd.addElement(mysqlDialect);  
    71.         mysqlDialect.addElement(new TextElement(  
    72.                 "limit #{page.start} , #{page.limit}"));  
    73.         paginationSuffixElement.addElement(pageEnd);  
    74.           
    75.         parentElement.addElement(paginationSuffixElement);  
    76.   
    77.         return super.sqlMapDocumentGenerated(document, introspectedTable);  
    78.     }  
    79.   
    80.     @Override  
    81.     public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(  
    82.             XmlElement element, IntrospectedTable introspectedTable) {  
    83.   
    84.         XmlElement pageStart = new XmlElement("include"); //$NON-NLS-1$     
    85.         pageStart.addAttribute(new Attribute("refid""OracleDialectPrefix"));  
    86.         element.getElements().add(0, pageStart);  
    87.   
    88.         XmlElement isNotNullElement = new XmlElement("include"); //$NON-NLS-1$     
    89.         isNotNullElement.addAttribute(new Attribute("refid",  
    90.                 "OracleDialectSuffix"));  
    91.         element.getElements().add(isNotNullElement);  
    92.   
    93.         return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element,  
    94.                 introspectedTable);  
    95.     }  
    96.   
    97.     /** 
    98.      * @param topLevelClass 
    99.      * @param introspectedTable 
    100.      * @param name 
    101.      */  
    102.     private void addDialect(TopLevelClass topLevelClass,  
    103.             IntrospectedTable introspectedTable, String name) {  
    104.         CommentGenerator commentGenerator = context.getCommentGenerator();  
    105.         Field field = new Field();  
    106.         field.setVisibility(JavaVisibility.PRIVATE);  
    107.         field.setType(new FullyQualifiedJavaType("String"));  
    108.         field.setName(name + " = "mysql"");  
    109.         commentGenerator.addFieldComment(field, introspectedTable);  
    110.         topLevelClass.addField(field);  
    111.         char c = name.charAt(0);  
    112.         String camel = Character.toUpperCase(c) + name.substring(1);  
    113.         Method method = new Method();  
    114.         method.setVisibility(JavaVisibility.PUBLIC);  
    115.         method.setName("set" + camel);  
    116.         method.addParameter(new Parameter(new FullyQualifiedJavaType(  
    117.                 "String"), name));  
    118.         method.addBodyLine("this." + name + "=" + name + ";");  
    119.         commentGenerator.addGeneralMethodComment(method, introspectedTable);  
    120.         topLevelClass.addMethod(method);  
    121.         method = new Method();  
    122.         method.setVisibility(JavaVisibility.PUBLIC);  
    123.         method.setReturnType(new FullyQualifiedJavaType(  
    124.                 "String"));  
    125.         method.setName("get" + camel);  
    126.         method.addBodyLine("return " + name + ";");  
    127.         commentGenerator.addGeneralMethodComment(method, introspectedTable);  
    128.         topLevelClass.addMethod(method);  
    129.     }  
    130.       
    131.     /** 
    132.      * @param topLevelClass 
    133.      * @param introspectedTable 
    134.      * @param name 
    135.      */  
    136.     private void addPage(TopLevelClass topLevelClass,  
    137.             IntrospectedTable introspectedTable, String name) {  
    138.         topLevelClass.addImportedType(new FullyQualifiedJavaType(  
    139.                 "com.hnisi.e3itm.base.util.Page"));  
    140.         CommentGenerator commentGenerator = context.getCommentGenerator();  
    141.         Field field = new Field();  
    142.         field.setVisibility(JavaVisibility.PROTECTED);  
    143.         field.setType(new FullyQualifiedJavaType("com.hnisi.e3itm.base.util.Page"));  
    144.         field.setName(name);  
    145.         commentGenerator.addFieldComment(field, introspectedTable);  
    146.         topLevelClass.addField(field);  
    147.         char c = name.charAt(0);  
    148.         String camel = Character.toUpperCase(c) + name.substring(1);  
    149.         Method method = new Method();  
    150.         method.setVisibility(JavaVisibility.PUBLIC);  
    151.         method.setName("set" + camel);  
    152.         method.addParameter(new Parameter(new FullyQualifiedJavaType(  
    153.                 "com.hnisi.e3itm.base.util.Page"), name));  
    154.         method.addBodyLine("this." + name + "=" + name + ";");  
    155.         commentGenerator.addGeneralMethodComment(method, introspectedTable);  
    156.         topLevelClass.addMethod(method);  
    157.         method = new Method();  
    158.         method.setVisibility(JavaVisibility.PUBLIC);  
    159.         method.setReturnType(new FullyQualifiedJavaType(  
    160.                 "com.hnisi.e3itm.base.util.Page"));  
    161.         method.setName("get" + camel);  
    162.         method.addBodyLine("return " + name + ";");  
    163.         commentGenerator.addGeneralMethodComment(method, introspectedTable);  
    164.         topLevelClass.addMethod(method);  
    165.     }  
    166.   
    167.     /** 
    168.      * This plugin is always valid - no properties are required 
    169.      */  
    170.     public boolean validate(List<String> warnings) {  
    171.         return true;  
    172.     }  
    173.       
    174.     public static void generate() {  
    175.         String config = PaginationPlugin.class.getClassLoader().getResource(  
    176.                 "generatorConfig.xml").getFile();  
    177.         String[] arg = { "-configfile", config, "-overwrite" };  
    178.         ShellRunner.main(arg);  
    179.     }  
    180.     public static void main(String[] args) {  
    181.         generate();  
    182.     }  
    183. }  


    ///////////////////////////////////////////////////////////////////////////////////////////////////////

    //////////////////////////////////////////////////////////////////////////////////////////////////////// mysql

    1. package org.leef.db.mybatis.plugin;  
    2. import java.util.List;  
    3. import org.mybatis.generator.api.CommentGenerator;  
    4. import org.mybatis.generator.api.IntrospectedTable;  
    5. import org.mybatis.generator.api.PluginAdapter;  
    6. import org.mybatis.generator.api.ShellRunner;  
    7. import org.mybatis.generator.api.dom.java.Field;  
    8. import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;  
    9. import org.mybatis.generator.api.dom.java.JavaVisibility;  
    10. import org.mybatis.generator.api.dom.java.Method;  
    11. import org.mybatis.generator.api.dom.java.Parameter;  
    12. import org.mybatis.generator.api.dom.java.TopLevelClass;  
    13. import org.mybatis.generator.api.dom.xml.Attribute;  
    14. import org.mybatis.generator.api.dom.xml.TextElement;  
    15. import org.mybatis.generator.api.dom.xml.XmlElement;  
    16. /** 
    17.  * <pre> 
    18.  * add pagination using mysql limit. 
    19.  * This class is only used in ibator code generator. 
    20.  * </pre> 
    21.  */  
    22. public class PaginationPlugin extends PluginAdapter {  
    23.     @Override  
    24.     public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,  
    25.             IntrospectedTable introspectedTable) {  
    26.         // add field, getter, setter for limit clause  
    27.         addLimit(topLevelClass, introspectedTable, "limitStart");  
    28.         addLimit(topLevelClass, introspectedTable, "limitEnd");  
    29.         return super.modelExampleClassGenerated(topLevelClass,  
    30.                 introspectedTable);  
    31.     }  
    32.     @Override  
    33.     public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(  
    34.             XmlElement element, IntrospectedTable introspectedTable) {  
    35.         XmlElement isParameterPresenteElemen = (XmlElement) element  
    36.                 .getElements().get(element.getElements().size() - 1);  
    37.         XmlElement isNotNullElement = new XmlElement("isGreaterEqual"); //$NON-NLS-1$  
    38.         isNotNullElement.addAttribute(new Attribute("property""limitStart")); //$NON-NLS-1$ //$NON-NLS-2$  
    39.         isNotNullElement.addAttribute(new Attribute("compareValue""0")); //$NON-NLS-1$ //$NON-NLS-2$  
    40.         isNotNullElement.addElement(new TextElement(  
    41.                 "limit $limitStart$ , $limitEnd$"));  
    42.         isParameterPresenteElemen.addElement(isNotNullElement);  
    43.         return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element,  
    44.                 introspectedTable);  
    45.     }  
    46.     private void addLimit(TopLevelClass topLevelClass,  
    47.             IntrospectedTable introspectedTable, String name) {  
    48.         CommentGenerator commentGenerator = context.getCommentGenerator();  
    49.         Field field = new Field();  
    50.         field.setVisibility(JavaVisibility.PROTECTED);  
    51.         field.setType(FullyQualifiedJavaType.getIntInstance());  
    52.         field.setName(name);  
    53.         field.setInitializationString("-1");  
    54.         commentGenerator.addFieldComment(field, introspectedTable);  
    55.         topLevelClass.addField(field);  
    56.         char c = name.charAt(0);  
    57.         String camel = Character.toUpperCase(c) + name.substring(1);  
    58.         Method method = new Method();  
    59.         method.setVisibility(JavaVisibility.PUBLIC);  
    60.         method.setName("set" + camel);  
    61.         method.addParameter(new Parameter(FullyQualifiedJavaType  
    62.                 .getIntInstance(), name));  
    63.         method.addBodyLine("this." + name + "=" + name + ";");  
    64.         commentGenerator.addGeneralMethodComment(method, introspectedTable);  
    65.         topLevelClass.addMethod(method);  
    66.         method = new Method();  
    67.         method.setVisibility(JavaVisibility.PUBLIC);  
    68.         method.setReturnType(FullyQualifiedJavaType.getIntInstance());  
    69.         method.setName("get" + camel);  
    70.         method.addBodyLine("return " + name + ";");  
    71.         commentGenerator.addGeneralMethodComment(method, introspectedTable);  
    72.         topLevelClass.addMethod(method);  
    73.     }  
    74.     /** 
    75.      * This plugin is always valid - no properties are required 
    76.      */  
    77.     public boolean validate(List<String> warnings) {  
    78.         return true;  
    79.     }  
    80.     public static void generate() {  
    81.         String config = PaginationPlugin.class.getClassLoader().getResource(  
    82.                 "generatorConfig.xml").getFile();  
    83.         String[] arg = { "-configfile", config, "-overwrite" };  
    84.         ShellRunner.main(arg);  
    85.     }  
    86.     public static void main(String[] args) {  
    87.         generate();  
    88.     }  
    89. }  
  • 相关阅读:
    php+redis简易消息队列
    Linux关闭selinux的方法(临时关闭和永久关闭)
    Linux清理buff/cache
    Centos禁止ping的设置方法
    浅谈mysql触发器
    mysql中left join right join inner join用法分析
    mysql主从配置详解(图文)
    mysql中的几种判断语句
    mysql锁表处理方法
    Mysql里的order by与索引
  • 原文地址:https://www.cnblogs.com/isoftware/p/3750219.html
Copyright © 2011-2022 走看看