(4)-mybatis之逆向工程:概念,結合maven工具使用步驟,CRUD案例,example案例

上一篇總結了mybatis之註解
這一篇總結逆向工程,下面一起來學吧

什麼是generator?

generator翻譯爲生成器,是MyBatis開源的一個插件,可以從數據庫獲取表信息,根據表信息自動生成Mapper.xml,POJO,以及Mapper接口

但問題是,MyBatis不可能完全清楚我們的業務需求,所以其自動生成的sql只能滿足基本的CRUD操作,而無法幫助我們進行連表操作,(當然包括帶有條件的CRUD)

使用步驟:

1.使用maven添加generator插件

<build>
    <plugins>
      <plugin>
      	<groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.7</version>
	      <configuration>
          			<!-- 是否覆蓋已存在的接口和POJO該配置不包括Mapper  
									若爲False將會生成版本記錄-->
                <overwrite>true</overwrite>
        </configuration>
        </plugin>
    </plugins>
</build>

如果pom.xml有build和plugins標籤,則只需把plugin標籤裏面內容加入plugins標籤裏面即可。在這裏有個注意:如果你的build標籤和plugins標籤之間有個pluginManagement標籤,則他是不下載插件的,需要把pluginManagement去掉,他就會自動下載,下載完會出現在你的maven插件裏面。

2.創建配置文件,位於resource下名爲generatorConfig.xml

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql:///student?characterEncoding=utf8&nullCatalogMeansCurrent=true
jdbc.user = root
jdbc.password = 123456
location = D:/maven/repository/mysql/mysql-connector-java/5.1.44/mysql-connector-java-5.1.44.jar


上面四個是數據庫配置文件,location是mysql驅動的位置,如果有,只需要在文件里加入location。不要忘了雙斜槓

3.創建配置文件,位於resource下名爲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>
    <!--導入屬性配置-->
    <properties resource="jdbc.properties"></properties>
    <!--指定特定數據庫的jdbc驅動jar包的位置-->
    <classPathEntry location="${location}"/>
    <context id="default" targetRuntime="MyBatis3">
        <!-- optional,旨在創建class時,對註釋進行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--jdbc的數據庫連接 -->
        <jdbcConnection
                driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.user}" password="${jdbc.password}">
        </jdbcConnection>

        <!-- 非必需,類型處理器,在數據庫類型和java類型之間的轉換控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!--Model模型生成器,用來生成含有主鍵key的類,記錄類 以及查詢Example類
        targetPackage 指定生成的model生成所在的包名
        targetProject 指定在該項目下所在的路徑 -->
        <javaModelGenerator targetPackage="com.cx.pojo" targetProject="src/main/java">
            <!-- 是否允許子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否對model添加 構造函數 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否對類CHAR類型的列的數據進行trim操作 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model對象是否 不可改變 即生成的Model對象不會有 setter方法,只有構造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!--mapper映射文件生成所在的目錄 爲每一個數據庫的表生成對應的SqlMap文件 -->
        <sqlMapGenerator targetPackage="com.cx.dao"
                         targetProject="src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!--mapper接口文件生成所在的目錄 爲每一個數據庫的表生成對應的接口文件 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.cx.dao" targetProject="src/main/java">
            <!-- enableSubPackages:是否讓schema(數據庫名稱)作爲包的後綴 -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>


        <!--指定需要生成的表-->
        <table  tableName="student"></table>
    </context>
</generatorConfiguration>




3.運行generator

在idea右側的maven菜單中雙擊執行mybatis-generator:generate

也可利用maven命令執行:mybatis-generator:generate

4.條件查詢使用pojo包,會發現每個pojo對應了一個Example。

在這裏插入圖片描述
generator的目標是儘可能的幫我們減少sql的編寫,如果只能進行簡單的增刪改查那編寫意義不大,於是generator使用了一套Example來幫助我們用OOP(面向對象)的方式來完成SQL中的條件拼接

其設計思想是將條件看做是一個對象,該對象包含了SQL中常見的比較,邏輯運算等…打開文件你會發現其本質就是幫我們拼接響應的sql符號和關鍵字

5.配置mybatis-config.xml文件

在mybatis-config.xml下要進行掃描包:

<!--    指定要加載的映射文件-->
    <mappers>
        <package name="com.cx.dao"/>
    </mappers>

6.CRUD案例

 private SqlSessionFactory sqlSessionFactory = null;
    @Before
    public void before() throws IOException {
        //加載核心配置文件
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
    }
    //查詢
    @Test
    public void test1(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);
        Product product = mapper.selectByPrimaryKey(2);
        System.out.println(product);
    }
    //插入
    @Test
    public void test2(){
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);
        Product product = new Product();
        product.setPname("香蕉");
        product.setPrice(3d);
        product.setPdate(new Date());
        mapper.insert(product);
    }
    //更新
    @Test
    public void test3(){
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);
        Product product = mapper.selectByPrimaryKey(2);
        product.setCid("s123456");
        mapper.updateByPrimaryKey(product);
    }
    //刪除
    @Test
    public void test4(){
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);
        mapper.deleteByPrimaryKey(6);
    }

7.example案例

import com.cx.dao.ProductMapper;
import com.cx.pojo.Product;
import com.cx.pojo.ProductExample;
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.Before;
import org.junit.Test;

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

public class Mytest3 {
    private SqlSessionFactory sqlSessionFactory;
    @Before
    public void before() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
    }
    //and條件
    @Test
    public void test1(){
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);
        //聲明對象
        ProductExample productExample = new ProductExample();
        //創建條件
        ProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andPidEqualTo(1);
        criteria.andPnameLike("%河南%");
        List<Product> products = mapper.selectByExample(productExample);
        System.out.println(products);
    }
    //or條件
    @Test
    public void test2(){
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);
        //聲明對象
        ProductExample productExample = new ProductExample();
        //創建一個條件對象,可以包含n個and
        ProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andPnameLike("香蕉");
        ProductExample.Criteria or = productExample.or();
        or.andCidEqualTo("s123456");
        List<Product> products = mapper.selectByExample(productExample);
        //最終結果爲name有香蕉或者cid爲  s123456
        System.out.println(products);
    }
}

注意:重新生成的Mapper文件時不會不會覆蓋之前的Mapper,而是會直接在裏面添加sql導致id衝突,所以重新生成mapper時一定要手動刪除已存在的mapper,否則可能會出現異常,例如:mybatis逆向工程Caused by: java.lang.IllegalArgumentException: Result Maps collection already contains va

總結

MyBatis逆向工程,幫助我們生成實體,接口,mapper文件
配置文件需要修改的地方:JDBC參數,驅動路徑,需要生成的表名稱,生成文件所在的包路徑

Example的使用,example主要是幫助我們實現條件查詢,在今後的開發中,是逆向工程中使用較多的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章