1、什么是 Mybatis逆向工程
MyBatis的一个主要的特点就是需要程序员自己编写sql,那么如果表太多的话,难免会很麻烦,所以mybatis官方提供了一个逆向工程,可以针对单表自动生成mybatis执行所需要的代码(包括mapper.xml、mapper.java、po…)。一般在开发中,常用的逆向工程方式是通过数据库的表生成代码。
2、使用方法
2、1导入jar包
<!-- MBG -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
2、2编写生成代码的mbg.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>
<!-- 一、配置数据库连接信息 -->
<!--targetRuntime=“MyBatis3“可以生成带条件的增删改查 -->
<!--targetRuntime=“MyBatis3Simple“可以生成基本的增删改查-->
<context id="DB2Tables" targetRuntime="MyBatis3Simple">
<!--去除注释-->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/***?serverTimezone=GMT"
userId="root"
password="******">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成pojo的位置 -->
<javaModelGenerator targetPackage="com.cmd.pojo"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成的sql映射文件 -->
<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 生成dao/mapper位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.cmd.dao"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 五、table指定每个表的生成策略 -->
<!--配置要逆向解析的数据表,tableName对应表名,domainObjectName对应实体类名-->
<table tableName="smbms_bill" domainObjectName="Bill"></table>
<table tableName="smbms_user" domainObjectName="User"></table>
2、3 编写生成代码的类
public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.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);
}
2、4 测试
这块自己测试