1. 首先我们新建一个genneratorConfigMysqL.xml文件, 把里面的数据库,用户名,数据库表都进行相应的替换,
domainObjectName是要生成的model文件名称
tableName 数据库表名
<?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="MysqLContext" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <property name="beginingDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <commentGenerator> <property name="supressDate" value="true"/> <property name="addRemarkComments" value="true"/> </commentGenerator> <jdbcConnection driverClass="com.MysqL.jdbc.Driver" connectionURL="jdbc:MysqL://xxxx?characterEncoding=utf8" userId="xxxx" password="xxxx" > </jdbcConnection> <javaModelGenerator targetPackage="test.qa.model" targetProject="src/main/java"> <property name="trimstrings" value="true"/> </javaModelGenerator> <sqlMapGenerator targetPackage="mybatis" targetProject="src/main/resources/"/> <javaClientGenerator type="XMLMAPPER" targetPackage="test.ke.dao" targetProject="src/main/java"/> <table tableName="xxxx" domainObjectName="xxxx"/> </context> </generatorConfiguration>View Code
2. 新建一个java文件,如下所示,运行即可生成对应的mapper.xml文件,model文件. 需要生成其他的数据库表的时候,只要替换genneratorConfigMysqL.xml文件中的数据库表名和要生成的model文件名即可
package test.util; 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.InputStream; import java.util.ArrayList; import java.util.List; /** * 生成model文件和xml文件。 需要修改generatorConfigMysqL.xml文件中的表和数据库 */ public class Generator { public static void main(String[] args) throws Exception{ List<String> warnings = new ArrayList<>(); boolean overwrite = true; InputStream is = Generator.class.getResourceAsstream("/generatorConfigMysqL.xml"); if(is == null){ System.out.println("null"); } ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(is); is.close(); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); for(String warning : warnings){ System.out.println(warning); } } }