关于mybatis的逆向工程中分页配置

关于mybatis的逆向工程中分页配置

因为在使用PageHelper插件的时候出现了异常的问题,所以考虑在数据库查询的时候直接进行分页操作,也就是在配置中添加limit,首先把我遇到的分页问题描述一下,如果有博友知道问题出现的原因,请告知,谢谢!


//设置分页信息
PageHelper.startPage(page, rows);
//执行查询
TbItemExample example = new TbItemExample();
List tbItems = tbItemMapper.selectByExample(example);
//取分页信息
PageInfo pageInfo = new PageInfo(tbItems);
//创建返回结果对象
EasyUIDataGridResult result = new EasyUIDataGridResult();
result.setTotal(pageInfo.getTotal());
result.setRows(tbItems);

      以上就是PageHelper的使用,但是在获取分页信息时出现一些问题,当在执行以下方法时,if条件总是不满足,所以导致不能正确分页,数据全部显示在页面,之后查找了许多资料也没能解决这个问题,为了不影响之后的操作,所以考虑在逆向工程生成时直接配置分页信息,关于if条件的问题,仍需深入研究。同时根据以上代码可知PageHelper是先把数据查出来之后取分页信息,个人觉得这种方式没有直接在sql中加limit方便。
      以下是有问题的if判断:

public PageInfo(List list, int navigatePages) {
        System.out.println(list instanceof Page);
        if (list instanceof Page) {
            Page page = (Page) list;
            this.pageNum = page.getPageNum();
            this.pageSize = page.getPageSize();

            this.total = page.getTotal();
            this.pages = page.getPages();
            this.list = page;
            this.size = page.size();
            //由于结果是>startRow的,所以实际的需要+1
            if (this.size == 0) {
                this.startRow = 0;
                this.endRow = 0;
            } else {
                this.startRow = page.getStartRow() + 1;
                //计算实际的endRow(最后一页的时候特殊)
                this.endRow = this.startRow - 1 + this.size;
            }
            this.navigatePages = navigatePages;
            //计算导航页
            calcNavigatepageNums();
            //计算前后页,第一页,最后一页
            calcPage();
            //判断页面边界
            judgePageBoudary();
        }
    }

之后就开始本文主要研究的问题,在逆向工程中添加分页配置


1、首先新建一个工程,并导入jar包,mybatis-generator-core-1.3.5.jar和mysql-connector-java-5.1.26-bin.jar,版本随意,maven仓库中就可以找到。
2、新建一个类,用于增加limit配置,以下配置除了增加分页之外还在逆向生成实体类的时候使实体类实现Serializable接口,方便使用,不然之后还要逐个添加。
关于mybatis的逆向工程中分页配置_第1张图片
这是我的目录结构,划掉的文件和本文无关。

生成类的具体代码如下:

package plugin;

import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.ShellRunner;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;

import java.util.List;
import java.util.Properties;

/**
 * Created by czy on 2018/2/1.
 */
public class PaginationPlugin extends PluginAdapter {

    private FullyQualifiedJavaType serializable;
    private FullyQualifiedJavaType gwtSerializable;
    private boolean addGWTInterface;
    private boolean suppressJavaInterface;

    @Override
    public void setProperties(Properties properties) {
        super.setProperties(properties);
        addGWTInterface = Boolean.valueOf(properties.getProperty("addGWTInterface")); //$NON-NLS-1$
        suppressJavaInterface = Boolean.valueOf(properties.getProperty("suppressJavaInterface")); //$NON-NLS-1$
    }

    public PaginationPlugin() {
        super();
        serializable = new FullyQualifiedJavaType("java.io.Serializable"); //$NON-NLS-1$
        gwtSerializable = new FullyQualifiedJavaType("com.google.gwt.user.client.rpc.IsSerializable"); //$NON-NLS-1$
    }

    /**
     * 给example添加序列化和分页设置
     *
     * @param topLevelClass
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        addLimit(topLevelClass, introspectedTable, "limitStart");
        addLimit(topLevelClass, introspectedTable, "limitEnd");
        makeSerializable(topLevelClass, introspectedTable);
        return super.modelExampleClassGenerated(topLevelClass, introspectedTable);
    }

    /**
     * 给实体类增加序列化设置
     *
     * @param topLevelClass
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        makeSerializable(topLevelClass, introspectedTable);
        return super.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
    }

    @Override
    public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        XmlElement isNotNullElement = new XmlElement("if");
        isNotNullElement.addAttribute(new Attribute("test", "limitStart != null and limitStart >= 0"));
        isNotNullElement.addElement(new TextElement("limit ${limitStart},${limitEnd}"));
        element.addElement(isNotNullElement);
        return super.sqlMapSelectByExampleWithoutBLOBsElementGenerated(element, introspectedTable);
    }

    private void makeSerializable(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        if (addGWTInterface) {
            topLevelClass.addImportedType(gwtSerializable);
            topLevelClass.addSuperInterface(gwtSerializable);
        }

        if (!suppressJavaInterface) {
            topLevelClass.addImportedType(serializable);
            topLevelClass.addSuperInterface(serializable);

            Field field = new Field();
            field.setFinal(true);
            field.setInitializationString("1L");
            field.setName("serialVersionUID");
            field.setStatic(true);
            field.setType(new FullyQualifiedJavaType("long"));
            field.setVisibility(JavaVisibility.PRIVATE);
            context.getCommentGenerator().addFieldComment(field, introspectedTable);

            topLevelClass.addField(field);
        }
    }

    private void addLimit(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, String name) {
        CommentGenerator commentGenerator = context.getCommentGenerator();
        //添加字段
        Field field = new Field();
        field.setVisibility(JavaVisibility.PROTECTED);
        field.setType(FullyQualifiedJavaType.getIntInstance());
        field.setName(name);
        field.setInitializationString("-1");
        commentGenerator.addFieldComment(field, introspectedTable);
        topLevelClass.addField(field);
        char c = name.charAt(0);
        //将首字母转为大写
        String camel = Character.toUpperCase(c) + name.substring(1);
        Method method = new Method();
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setName("set" + camel);
        method.addParameter(new Parameter(FullyQualifiedJavaType.getIntInstance(), name));
        method.addBodyLine("this." + name + "=" + name + ";");
        commentGenerator.addGeneralMethodComment(method, introspectedTable);
        topLevelClass.addMethod(method);
        method = new Method();
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setReturnType(FullyQualifiedJavaType.getIntInstance());
        method.setName("get" + camel);
        method.addBodyLine("return " + name + ";");
        commentGenerator.addGeneralMethodComment(method, introspectedTable);
        topLevelClass.addMethod(method);
    }

    @Override
    public boolean validate(List list) {
        return true;
    }

    public static void generate() {
        String config = PaginationPlugin.class.getClassLoader().getResource("mybatisConfig.xml").getFile();
        String[] args = {"-configfile", config, "-overwrite"};
        ShellRunner.main(args);
    }

    public static void main(String[] args) {
        generate();
    }
}

3、和数据库相连接的具体配置:




<generatorConfiguration>
    <context id="DB2Tables">
        <plugin type="plugin.PaginationPlugin" />
        <commentGenerator>
            
            <property name="suppressAllComments" value="true" />
        commentGenerator>

        
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test"
                        userId="root"
                        password="000000">
        jdbcConnection>


        
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        javaTypeResolver>

        
        <javaModelGenerator targetProject="D:\mysqlToClass" targetPackage="po">
            
            <property name="trimStrings" value="true" />
        javaModelGenerator>

        
        <sqlMapGenerator targetPackage="mapping" targetProject="D:\mysqlToClass">
        sqlMapGenerator>

        
        <javaClientGenerator type="XMLMAPPER" targetPackage="mapper" targetProject="D:\mysqlToClass">
        javaClientGenerator>
        
        

        
        
        <table tableName="%">table>

        
        
        
    context>
generatorConfiguration>

运行后的结果:
关于mybatis的逆向工程中分页配置_第2张图片

4、将生成的类和xml文件放在相应的位置,进行分页测试,我的项目还有其他的操作,读者可以根据自己需求进行测试。
      将最开始的方法进行改造,改造后的结果为:

public EasyUIDataGridResult getItemList(int page, int pageSize) {
        //执行查询
        TbItemExample example = new TbItemExample();
        //创建返回结果对象
        EasyUIDataGridResult result = new EasyUIDataGridResult();

        result.setTotal(tbItemMapper.countByExample(example));
        example.setLimitStart(page * pageSize);
        example.setLimitEnd(pageSize);
        List tbItems = tbItemMapper.selectByExample(example);

        result.setRows(tbItems);
        return result;
    }

之后就可以正常分页,不使用PageHelper。

你可能感兴趣的:(数据库,mybatis)