mybatis代码生成器实现方式
1.pom
<dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.4.0</version> </dependency>
2.mybatis-generator/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="MySqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <commentGenerator> <property name="suppressDate" value="true"/> <property name="addRemarkComments" value="true"/> <property name="suppressAllComments" value="true"/> </commentGenerator> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/blog" userId="root" password="123456"> </jdbcConnection> <javaModelGenerator targetPackage="com.pab.data.datasource.entity" targetProject="src\main\java"> <property name="trimStrings" value="true"/> </javaModelGenerator> <sqlMapGenerator targetPackage="mapper" targetProject="src\main\resources"> </sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="com.pab.data.datasource.mapper" targetProject="src\main\java"> </javaClientGenerator> <!-- <table tableName="%">--> <!--指定表--> <table tableName="employee"> <generatedKey column="id" sqlStatement="MySql"/> </table> </context> </generatorConfiguration>
3.mybatis 代码生成器
/** * mybaits代码生成器 */ public class Generator { public static void main(String[] args) throws Exception { //MBG 执行过程中的警告信息 List<String> warnings = new ArrayList<String>(); //当生成的代码重复时,覆盖原代码 boolean overwrite = true; //读取我们的 MBG 配置文件 InputStream is = org.mybatis.generator.api.MyBatisGenerator.class.getResourceAsStream("/mybatis-generator/generatorConfig.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(is); is.close(); DefaultShellCallback callback = new DefaultShellCallback(overwrite); //创建 MBG org.mybatis.generator.api.MyBatisGenerator myBatisGenerator = new org.mybatis.generator.api.MyBatisGenerator(config, callback, warnings); //执行生成代码 myBatisGenerator.generate(null); //输出警告信息 for (String warning : warnings) { System.out.println(warning); } } }