逆向工程:通过数据库中的单表,自动生成java代码
下载地址:https://github.com/mybatis/generator/releases
使用方法:
- 1.创建简单项目/maven
- 2.导包/pom.xml添加依赖
- 3.创建generator配置文件
- 4.main方法运行
- 5.复制生成的代码到工程
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>
<!--mysql数据库,mybatis版本3-->
<context id="mysqlTables" targetRuntime="MyBatis3">
<!--数据库配置-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/db_mybatis"
userId="root"
password="root">
</jdbcConnection>
<!-- java类型解析 -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 模型生成包名 生成位置 -->
<javaModelGenerator targetPackage="com.zjc.model" targetProject=".\src">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- mybatis的映射.xml 生成位置 -->
<sqlMapGenerator targetPackage="com.zjc.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- mybatis 的mapper接口生成的包路径 生成位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.zjc.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 配置生成表的模型-->
<table tableName="users"></table>
</context>
</generatorConfiguration>
main方法:入口
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("src/generator.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);
}
maven:pom.xml (个人觉得方便)
<dependency>
<groupId>org.apache.ibatis</groupId>
<artifactId>ibatis-core</artifactId>
<version>3.0</version>
</dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>