1. 程式人生 > >MyBatis逆向工程-根據資料庫表自動生成bean、mapper介面以及對映檔案

MyBatis逆向工程-根據資料庫表自動生成bean、mapper介面以及對映檔案

說明:偶然看到一個視訊,講到了使用mybatis的逆向工程實現自動生成程式碼的部分(根據資料表生成相應的實體類、對映檔案、介面),因為之前沒有學習過這類東西,今天照著弄了下,然後自己寫了一個測試案例,特來記錄。。。。

=============================================

1.首先是maven結構的專案(以下圈起來的部分不需要我們編寫,是由mybatis逆向工程生成的)


------------------------------------------------------------

2.資料表比較簡單,僅僅只是為了測試生成程式碼的過程是否成功。表結構如下


--------------------------------------------------------------

3.首先先看需要載入的依賴

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.lin</groupId>
  <artifactId>MyBatisGeneratorTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

	<dependencies>
	    <!-- MyBatis -->
	    <dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis</artifactId>
		<version>3.4.5</version>
	    </dependency>
		<!-- MyBati Generator逆向工程(程式碼生成器) -->
		<dependency>
		    <groupId>org.mybatis.generator</groupId>
		    <artifactId>mybatis-generator-core</artifactId>
		    <version>1.3.5</version>
		</dependency>
		
		
	  <dependency>  
            <groupId>mysql</groupId>  
            <artifactId>mysql-connector-java</artifactId>  
            <version>5.1.30</version>  
        </dependency>
		
		
	<dependency>  
            <groupId>log4j</groupId>  
            <artifactId>log4j</artifactId>  
            <version>1.2.17</version>  
        </dependency>
		
	</dependencies>


 <!-- 新增專案jdk編譯外掛 -->
  <build>
  	<!-- 設定編譯版本為1.8 -->
  	<plugins>
  		<plugin>
  			<groupId>org.apache.maven.plugins</groupId>
  			<artifactId>maven-compiler-plugin</artifactId>
  			<configuration>
  				<source>1.8</source>
  				<target>1.8</target>
  				<encoding>UTF-8</encoding>
  			</configuration>
  		</plugin>
  		<!-- 配置tomcat7的外掛,如果使用maven的命令方式執行,則命令為:tomcat7:run ,
  			 而不能是tomcat:run(如果使用該命令,還是會使用maven預設的tomcat來編譯執行專案)。
  			
  			可以直接使用eclipse中的tomcat來執行專案(就是原先沒有使用maven時的那樣執行專案就可以了,那樣的話也不需要配這個外掛了)。	 
  		 -->
  		<plugin>  
            <groupId>org.apache.tomcat.maven</groupId>  
            <artifactId>tomcat7-maven-plugin</artifactId>  
            <version>2.1</version>
        </plugin>
  	</plugins>
  </build>
  
</project>

4.然後搭建mybatis的執行環境

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration 
	PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	
	<settings>
		<!-- 要使延遲載入生效必須配置下面兩個屬性 -->
		<!-- lazyLoadingEnabled屬性表示延遲載入的全域性開關,預設為false -->
		<setting name="lazyLoadingEnabled" value="true"/>
		<!-- aggressiveLazyLoading屬性啟用時,會使帶有延遲載入屬性的物件立即載入;反之,會按需載入。預設為true -->
		<setting name="aggressiveLazyLoading" value="false"/>
	</settings>
	
	<!-- 定義資料庫資訊,預設使用development資料庫構建環境 -->
	<environments default="development">
		<environment id="development">
			<!-- 採用JDBC事務管理 -->
			<transactionManager type="JDBC"/>
			<!-- 配置資料庫連線資訊 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/maven"/>
				<property name="username" value="root"/>
				<property name="password" value="546784"/>
			</dataSource>
		</environment>
	</environments>
	 
	<!-- 定義對映器,載入對映檔案 -->
	<mappers>
		<package name="com.lin.mapper"/>
	</mappers>
	
</configuration>

-----------------------------------------------------------------

5.然後就是本測試最重要的逆向工程配置了,其配置檔案參考的官方文件http://www.mybatis.org/generator/afterRunning.html。。。具體說明在註解中標的詳細了(這是比較簡單的配置,但是應對普通的開發還是可以用的。。)

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="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/maven"
        userId="root"
        password="546784">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

	<!-- 指定javabean生成的位置 
		targetPackage:在哪個包下生成
		targetProject:在哪個工程下
	-->
    <javaModelGenerator targetPackage="com.lin.domain"
    	 targetProject=".\src\main\java">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

	<!-- 指定sql對映檔案生成的位置 -->
    <sqlMapGenerator targetPackage="com.lin.mapper"  
    	targetProject=".\src\main\java">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

	<!-- 指定到介面生成的位置 ,mapper介面 -->
    <javaClientGenerator type="XMLMAPPER" 
    	targetPackage="com.lin.mapper"  
    	targetProject=".\src\main\java">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

	<!-- 指定每個表的生成策略 -->
    <table tableName="t_user" domainObjectName="User"></table>
  </context>
</generatorConfiguration>

------------------------------------------

6.然後要編寫一個來執行逆向工程的程式碼(這段程式碼具體是什麼意思我也沒有搞懂,但是以下需要我們指定的就是mbg.xml檔案所在的位置,然後執行就可以生成我們所需要的程式碼了

MBGTest.java

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);
	}
}

---------------------------------------------------------------------

OK,以上就可以生成我們所需要的程式碼了(

PS:

生成後會多出一個類


看視訊上的介紹是說這個是用來做複雜查詢用的,但是不知道是我配置錯了還是怎麼回事,這個生成的類跟我實際的業務完全不相關。。。還有值得一提的是,生成的對映檔案還是得需要我們手動的進行部分的修改,因為不會完全的符合我們預期的效果的。),但是不影響我們使用別的生成的檔案就是了,接下來簡單測試一下是否可以執行

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.lin.domain.User;
import com.lin.mapper.UserMapper;

public class MybatisTest {
    
    //根據使用者id查詢使用者資訊
    @Test
    public void insertUser() throws Exception {
        //ͨ定義SqlSession
        SqlSession sqlSession = null;
        try {
            //讀取MyBatis的全域性配置檔案
            String resource = "mybatis/mybatis-config.xml";
            //讀取MyBatis的全域性配置檔案
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //根據流物件獲取會話工廠sqlSessionFactory
            SqlSessionFactory  sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //建立會話sqlSession
            sqlSession = sqlSessionFactory.openSession();
            //通過sqlSession執行對資料庫的相關操作
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            //測試插入一條資料
//            User u = new User();
//            u.setUserId(1);
//            u.setUserName("lin");
//            int i = userMapper.insert(u);
//            //這裡一定要提交事務,不然不會更新到資料庫!!!
//            sqlSession.commit();
//            System.out.println("成功插入了"+i+"條資料!");
            //測試按主鍵查詢使用者
            User u = userMapper.selectByPrimaryKey(1);
            System.out.println(u.getUserName()+"  "+u.getUserId());
            
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //關閉會話
            sqlSession.close();
        }
        
    }
}

=====================================================

到這裡,逆向工程所生成的檔案就可以使用了~~~