生成xml文件,文件名generator.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="mysqlTables" targetRuntime="MyBatis3">
<!-- 数据库配置 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatisday1?useUnicode=true&characterEncoding=utf8"
userId="root"
password="123456">
</jdbcConnection>
<!-- java类型解析 -->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 配置模型生成包名-->
<javaModelGenerator targetPackage="com.wenhe.model" targetProject=".\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--mybatis的映射.xml-->
<sqlMapGenerator targetPackage="com.wenhe.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!--mybatis 的mapper接口生成的包路径-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.wenhe.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 配置生成表的模型 -->
<!--tableName是数据库表名-->
<table tableName="items" domainObjectName="Items" ></table>
<table tableName="orderdetail" domainObjectName="orderDetail" ></table>
<table tableName="orders" domainObjectName="Orders" ></table>
<table tableName="user" domainObjectName="User" ></table>
</context>
</generatorConfiguration>
测试代码
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args)throws Exception {
List<String> strings = new ArrayList<>();
boolean overwrite = true;
File configFile = new File("src/generator.xml");
ConfigurationParser cp = new ConfigurationParser(strings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, strings);
myBatisGenerator.generate(null);
}
}