什么是逆向工程
在传统开发中,开发者需要自己去写实体类、SQL语句、Dao层的方法等。Mybatis为我们提供了逆向工程,只需要指定数据库的表,Mybatis就能自动生成实体类和mapper映射。大大节约了开发时间。
步骤
搭建Mybatis框架
前面Mybatis入门有讲,此处略。
引入Mybatis逆向工程包
传统开发搜索Mybatis Generate,下载包并导入。
Maven开发直接引入。
建立逆向工程配置文件
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>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<jdbcConnection driverClass="驱动包"
connectionURL="数据库地址"
userId="用户名" password="密码">
</jdbcConnection>
<javaTypeResolver>
<!-- 是否强制设置为大数 否的话则根据字段长度生成数据类型 -->
<property name="forceBigDecimals" value="false" />
<!-- 使用表字段名作为属性名 -->
<property name="useActualColumnNames" value="true" />
</javaTypeResolver>
<!--生成entity类存放位置 -->
<javaModelGenerator
targetPackage="com.kx.promote.bean" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--生成映射文件存放位置 -->
<sqlMapGenerator targetPackage="mapper"
targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!--生成Dao类存放位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.kx.promote.dao" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 需要逆向工程操作的表 -->
<table tableName="boss" domainObjectName="Boss"></table>
<table tableName="file" domainObjectName="File"></table>
<table tableName="group" domainObjectName="Group"></table>
<table tableName="need" domainObjectName="Need"></table>
<table tableName="order" domainObjectName="Order"></table>
<table tableName="shop" domainObjectName="Shop"></table>
<table tableName="user" domainObjectName="User"></table>
</context>
</generatorConfiguration>
建立逆向工程执行类
MBGTest.java:
package com.kx.promote.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
public class MBGTest {
public static void main(String[] args) throws Exception {
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);
}
}
运行
运行,刷新一下项目目录,看看是否成功导入。
Comments | NOTHING