MyBatis Generator是一个非常方便的代码生成工具,它能够根据表结构生成CRUD代码,可以满足大部分需求。但是唯一让人不爽的是,生成的代码中的数据库查询没有分页功能。本文介绍如何让MyBatis Generator生成的代码具有分页功能。
MyBatis Generator结合Maven的配置和使用
在实现分页之前,首先简单介绍MyBatis Generator如何使用。
MyBatis Generator配置文件
MyBatis Generator通常会有一个xml配置文件,用来指定连接的数据库、哪些表、如何生成代码。详情可以参考官方文档:http://www.mybatis.org/generator/configreference/xmlconfig.html 。下面给出一份简单的配置,文件命名为generatorConfig.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="mysqlgenerator" targetRuntime="MyBatis3">
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/yourdb?useUnicode=true&characterEncoding=UTF-8"
userId="user" password="password" />
<javaModelGenerator targetPackage="com.xxg.bean" targetProject="src/main/java" />
<sqlMapGenerator targetPackage="com.xxg.mapper" targetProject="src/main/resources" />
<javaClientGenerator type="XMLMAPPER" targetPackage="com.xxg.mapper" targetProject="src/main/java" />
<table tableName="table_a" />
<table tableName="table_b" />
<table tableName="table_c" />
<table tableName="table_d" />
</context>
</generatorConfiguration>
Maven配置
官网文档中提供了四种MyBatis Generator生成代码的运行方式:命令行、使用Ant、使用Maven、Java编码。本文采用Maven插件mybatis-generator-maven-plugin来运行MyBatis Generator,详细配置同样可以参考官方文档:http://www.mybatis.org/generator/running/runningWithMaven.html 。下面给出一份简单的pom.xml的配置:
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin