Mybatis 提供了一个逆向工程工具,该工具可以根据数据表自动生成针对 单表 的 po 类、mapper 映射文件和 mapper 接口。大大缩减了开发时间,可以让开发人员将更多的精力放在繁杂的业务逻辑上。
示例表结构:
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(10) DEFAULT NULL,
`price` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
7.10.1 引入Jar包
maven 项目在 pom.xml 文件中添加以下代码。
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
7.10.2 创建配置文件
新建资源文件夹 config,在 config 文件夹下创建 generatorConfig.xml 文件,用于配置及指定数据库及表等。
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="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- Mysql数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://xxxx:3306/mybatis" userId="root"
password="123" />
<!-- 默认为false,把JDBC DECIMAL 和NUMERIC类型解析为Integer,为true时 把JDBC DECIMAL 和NUMERIC类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成POJO类的位置 -->
<javaModelGenerator
targetPackage="cn.dt.mybatis.pojo" targetProject=".\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="mybatis"
targetProject=".\src\main\resources">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetProject:mapper接口生成的的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="cn.dt.mybatis.mapper" targetProject=".\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据表 -->
<table tableName="product"></table>
</context>
</generatorConfiguration>
7.10.3 创建 GeneratorSqlmap 类执行生成代码
public class GeneratorTest {
@Test
public void generator() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
// 指定配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(resourceAsStream);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}
执行以上代码可以生成 POJO 类,Mapper 接口及 Mapper 映射文件, 需要手动将 Mapper 映射文件加入 MyBatis 配置文件。
<configuration>
......
<mappers>
......
<mapper resource="mybatis/ProductMapper.xml"/>
......
</mappers>
</configuration>
7.10.4 运行测试
@Test
public void testInsert(){
ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
Product r = new Product();
r.setName("book");
productMapper.insert(r);
}
@Test
public void testSelectByExample() {
ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
ProductExample e = new ProductExample();
e.setDistinct(true);
e.setOrderByClause("name, price desc");
e.createCriteria()
.andPriceIsNull()
.andNameEqualTo("book");
productMapper.selectByExample(e).forEach(System.out::println);
}
执行结果:
18:08:54.700 [Test worker] DEBUG cn.dt.mybatis.mapper.ProductMapper.insert - ==> Preparing: insert into product (id, name, price ) values (?, ?, ? )
18:08:54.802 [Test worker] DEBUG cn.dt.mybatis.mapper.ProductMapper.insert - > Parameters: null, book(String), null
18:08:54.809 [Test worker] DEBUG cn.dt.mybatis.mapper.ProductMapper.insert - < Updates: 1
18:08:54.918 [Test worker] DEBUG cn.dt.mybatis.mapper.ProductMapper.selectByExample - ==> Preparing: select distinct id, name, price from product WHERE ( price is null and name = ? ) order by name, price desc
18:08:54.919 [Test worker] DEBUG cn.dt.mybatis.mapper.ProductMapper.selectByExample - > Parameters: book(String)
18:08:54.986 [Test worker] DEBUG cn.dt.mybatis.mapper.ProductMapper.selectByExample - < Total: 4
Product(id=1, name=book, price=null)
Product(id=2, name=book, price=null)
Product(id=3, name=book, price=null)
Product(id=4, name=book, price=null)
更多信息可参考《MyBatis逆向工程使用手册》。