Mybatis-Generator代码生成器官方文档
第一步 :加入依赖:
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
第二步 :建立generatorConfig.xml文件
<!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:随便写
targetRuntime:生成策略
MyBatis3DynamicSql:默认的,会生成 动态生产sql的方式(没有xml)
MyBatis3:生成通用的查询,可以指定动态where条件
MyBatis3Simple:只生成简单的CRUD
-->
<context id="simple" targetRuntime="MyBatis3">
<!--不会使代码生成注释-->
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据源-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="root"
password="123456"/>
<!--
总指定:
javaModelGenerator:java实体类生成规则
sqlMapGenerator:mapper.xml映射文件生成规则
javaClientGenerator:mapper接口生成规则
targetPackage:生成到哪个包下
targetProject:生成到当前文件的哪个相对路径下
-->
<!--pojo-->
<javaModelGenerator targetPackage="com.mofei.pojo" targetProject="src/main/java"/>
<!--mapper.xml配置文件-->
<sqlMapGenerator targetPackage="com.mofei.mapper" targetProject="src/main/java"></sqlMapGenerator>
<!--mapper接口
其中type为指定生成方式:
1,使用注解方式生成
2,使用接口绑定的方式生成
-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.mofei.mapper" targetProject="src/main/java"/>
<!--配置完以上内容以后再说明哪些表需要配置说明
tableName:表名
domainObjectName:pojo类名
mapperName:对应mapper接口的类名 和 mapper.xml文件名
-->
<table tableName="blog" domainObjectName="Blog" mapperName="BlogMapper" />
<table tableName="student" domainObjectName="Student" mapperName="StudentMapper" />
<table tableName="teacher" domainObjectName="Teacher" mapperName="TeacherMapper" />
</context>
</generatorConfiguration>
第三步:使用测试方法运行生成相关文件:
@Test
public void testMybatisGenerator() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}