概念
Mybatis的逆向工程(原理+详细操作)_曾吹雨的博客-CSDN博客_mybatis逆向工程原理
- 正向工程:先创建Java实体类,由框架负责根据实体类生成数据库表。Hibernate是支持正向工程的。
- 逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成如下资源:
Java实体类
Mapper接口
Mapper配置文件
步骤
导入jar包
1 2 3 4 5 6
| <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.4.1</version> </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
| <?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="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/school" userId="root" password="200101" />
<javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver>
<javaModelGenerator targetPackage="com.zss.pojo" 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.zss.dao" targetProject=".\src\main\java"> <property name="enableSubPackages" value="false" /> </javaClientGenerator>
<table tableName="tb_emp" domainObjectName="Employee"/> <table tableName="tb_dept" domainObjectName="Department"/>
</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 28 29 30 31 32
| package com.zss.Test;
import java.io.File; import java.util.*; 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 GeneratorSqlmap { public void generator() throws Exception { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("src/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); }
public static void main(String[] args) { try { GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap(); generatorSqlmap.generator(); } catch (Exception e) { e.printStackTrace(); } } }
|