1. 程式人生 > >SpringCloud+MyBatis(oracle)逆向工程自動生成程式碼

SpringCloud+MyBatis(oracle)逆向工程自動生成程式碼

一、何為逆向工程?

    平時我們的開發過程,除了系統框架的搭建。其他無非就是CRUD增刪改查的程式碼邏輯搬磚,CRUD也就避免不了要跟資料庫打交道。一般常見的資料庫操作insert(增)、update(改)、select(查)、delete(刪);常規傳統的資料庫層面開發,涉及如下過程:

1、建立資料庫DB連線(已有表)

2、實體類/POJO/Mapper.xml

3、程式增刪改查操作

其中,第二步:實體類/POJO/XML等;都是由手工編寫的程式碼和xml檔案,此為正向工程。

二、為何逆向工程?

如一所述:正向工程,人為手工編寫程式碼實體類/POJO/Mapper.xml等,很多操作都是重複並冗餘的。比如:實體類,其實就是資料庫表的一個對映,把表字段一個個列出來並設定getter/setter方法以便程式使用。pojo,select、update、delete、insert方法也都是千篇一律,無非就是方法不同,引數各異。xml,就是SQL語句的整合與資料庫互動的連線點;對於同一個專案而言資料庫連線相同,專案路徑一樣等。

    如果:可以自動生成實體類、pojo、xml等,那麼可以減輕很多重複人為工作量,轉而由機器自動生成,當資料庫表操作量大的話,會節省很多的時間。

三、Spring中MyBatis逆向工程操作步驟

  • Maven新增依賴
  • generatorConfig.xml配置
  • 資料庫連線配置、實體類/POJO/XML生成路徑
  • 指定資料庫表
  • java class用於自動生成的main方法

1、Maven依賴,包括ojdbc資料庫連線、mybatis支援、spring-mybatis外掛這幾大類。

SpringBoot對MyBatis外掛的支援:

        <dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>

自動生成mybatis-generator-core依賴引入(核心):

			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.2</version>
				<dependencies>
					<dependency>
						<groupId>org.mybatis.generator</groupId>
						<artifactId>mybatis-generator-core</artifactId>
						<version>1.3.2</version>
					</dependency>
				</dependencies>
			</plugin>

2、generatorConfig.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>

	<classPathEntry
		location="C:\Users\Administrator\.m2\repository\com\oracle\ojdbc6\11.1.0.7.0\ojdbc6-11.1.0.7.0.jar" />
	<context id="context1"> 
		<property name="javaFileEncoding" value="UTF-8" />
		<commentGenerator type="com.**nks.e**s.CustomCommentGenerator" >
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

		<jdbcConnection connectionURL="jdbc:oracle:thin:@//1**.20.19.2**:1521/p**y"
			driverClass="oracle.jdbc.driver.OracleDriver" password="***#123"
			userId="**s">
			<!-- 針對oracle資料庫 -->
			<property name="remarksReporting" value="true"></property>
		</jdbcConnection>


		<javaModelGenerator targetPackage="com.**nks.**ps.pas.tmp"
			targetProject="src\main\java\com\**links\**ps\pas\tmp" />

		<sqlMapGenerator targetPackage="com.**links.**ps.pas.tmp"
			targetProject="src\main\java\com\**links\**ps\pas\tmp" />

		<javaClientGenerator targetPackage="com.**links.**ps.pas.tmp"
			targetProject="src\main\java\com\**links\**ps\pas\tmp" type="XMLMAPPER" />


		<table tableName="CUM_WITHDRAW_COUNT_RECORD" domainObjectName="WithdrawCountRecord"
			   enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
			   enableSelectByExample="false" selectByExampleQueryId="false">
		</table>
	</context>
</generatorConfiguration>

3、CustomCommentGenerator自動生成的啟動main方法入口class檔案

package com.**links.**ps;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class CustomCommentGenerator extends DefaultCommentGenerator {
	@Override
	public void addFieldComment(Field field, IntrospectedTable introspectedTable,
			IntrospectedColumn introspectedColumn) {
		// 新增欄位註釋 
		field.addJavaDocLine("/**"); 
		if (introspectedColumn.getRemarks() != null) {
            field.addJavaDocLine(" * " + introspectedColumn.getRemarks());
        }
		 // addJavadocTag(field, false);
		field.addJavaDocLine(" */");
	}
	
	
	public static void main(String[] args) throws Exception {
        try {
            List<String> warnings = new ArrayList();
            boolean overwrite = true;
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream is = classloader.getResourceAsStream("generatorConfig.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(is);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }

}

按照上述步驟都做好之後,在不需要啟動專案的前提下,即可自動生成程式碼。

右鍵單擊CustomCommentGenerator類,選擇run或debug

接下來,程式就自動生成指定的表所需要的實體類、POJO、mapper.xml

如下所示:

帶有註釋的實體類

如此,整個過程的步驟都完成了。

注:這裡的生成路徑是樓主自己建的臨時路徑資料夾src\main\java\com\**links\**ps\pas\tmp,然後再如果有批量的表需要自動生成,則只需在generatorConfig.xml檔案中配置多個table即可。


		<table tableName="tableName***" domainObjectName="pojoName***"
			   enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
			   enableSelectByExample="false" selectByExampleQueryId="false">
		</table>
......

MyBatis的逆向工程,給我們開發帶來很大的便利。是開發者必須要掌握的技術,分享到這裡;覺得有幫助隨手給個贊和轉發一下。

關注個人技術公眾號:nick_coding1024

不定期分享最新前沿技術框架和bat大廠常用技術等,加群不定期分享行業內大牛直播講課以及獲得內退一線網際網路公司機會。