确保建立了一个基于maven管理的mybatis项目,且已经将三层架构以及entity包完整创建,包括mapper映射文件夹,sql配置文件夹等,
在main文件夹中导入如下代码(以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>
<!--是否去除注释,true表示是,false否-->
<property name="suppressAllComments" value="true"></property>
</commentGenerator>
<!--数据库连接信息-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/user?characterEncoding=utf-8"
userId="root"
password="root"
></jdbcConnection>
<!--设置数据类型的转化
默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,
true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal
-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"></property>
</javaTypeResolver>
<!--设置实体类配置
targetPackage:实体类的包名
targetProject:放在哪个项目包下
-->
<javaModelGenerator targetPackage="com.softxxx.lis0915.entity" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"></property>
<property name="trimStrings" value="true"></property>
</javaModelGenerator>
<!--sql映射文件配置-->
<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true"></property>
</sqlMapGenerator>
<!--mapper接口配置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.softxxx.lis0915.mapper" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!--数据库与实体映射-->
<table tableName="book" domainObjectName="Book"></table>
</context>
</generatorConfiguration>
在测试类中加入如下代码
package com.softxxx.lis0915.Text;
import org.junit.Test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MybatisGeneratorTest {
@Test
public void mybatisGeneratorTest() throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
List<String> list = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mg.XML");
ConfigurationParser cp = new ConfigurationParser(list);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, list);
myBatisGenerator.generate(null);
}
}
点击运行后即可构建。