逆向工程
可以针对单表自动生成MyBatis执行所需要的代码,包括:Mapper.java,Mapper.xml,实体类,这样可以减少重复代码的编写
1 2 3 4
| <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> </dependency>
|
逆向工程配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| <?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="testTables" targetRuntime="MyBatis3">
<commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8" userId="root" password="123456"> </jdbcConnection>
<javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver>
<javaModelGenerator targetPackage="com.zhanghe.study.mybatis.model" targetProject="./src/main/java"> <property name="enableSubPackages" value="false" /> <property name="trimStrings" value="true" /> </javaModelGenerator>
<sqlMapGenerator targetPackage="mapper" targetProject="./src/main/resources"> <property name="enableSubPackages" value="false" /> </sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.zhanghe.study.mybatis.mapper" targetProject="./src/main/java"> <property name="enableSubPackages" value="false" /> </javaClientGenerator>
<table tableName="student" domainObjectName="Student"/>
</context> </generatorConfiguration>
|
执行类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class GeneratorMain { public static void main(String[] args) { List<String> warnings = new ArrayList<>(); boolean overwrite = true; String genCfg = "generatorConfig.xml"; File configFile = new File(Thread.currentThread().getContextClassLoader().getResource(genCfg).getFile()); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = null; try { config = cp.parseConfiguration(configFile); } catch (IOException | XMLParserException e) { e.printStackTrace(); } DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = null; try { myBatisGenerator = new MyBatisGenerator(config, callback, warnings); } catch (InvalidConfigurationException e) { e.printStackTrace(); } try { myBatisGenerator.generate(null); } catch (SQLException | IOException | InterruptedException e) { e.printStackTrace(); } } }
|
idea配置的坑
idea中的默认是相对于工作空间的路径,需要改一下edit Configurations中的Working directory为$ModuleFileDir$
当然最好是配置一下Templates,这样就不需要每一个进行修改了