真贊!IDEA 中這麼玩 MyBatis,讓編碼速度飛起!

點擊上方“芋道源碼”,選擇“設爲星標

管她前浪,還是後浪?

能浪的浪,纔是好浪!

每天 8:55 更新文章,每天掉億點點頭髮...

源碼精品專欄

 

來源:cnblogs.com/java-class/p/6237564.html

  • 1. 搭建 MyBatis Generator 插件環境

    • a. 添加插件依賴 pom.xml

    • b. 配置文件 generatorConfig.xml

    • c. 數據庫配置文件 jdbc.properties

    • d. 配置插件啓動項

  • 2.項目實戰

    • a. 比如在一個項目 我們要刪除某個小組下某個用戶的信息

    • b. 根據小組ID(非主鍵 更新小組信息)

    • c. 各種查詢


IDEA 逆向 MyBatis 工程時,不像支持 Hibernate 那樣有自帶插件,需要集成第三方的 MyBatis Generator。

MyBatis Generator的詳細介紹 http://mybatis.github.io/generator/index.html

本篇博客圖解 MyBatis Generator 的使用過程,並結合實戰說明逆向工程的使用方式。

1. 搭建 MyBatis Generator 插件環境

a. 添加插件依賴 pom.xml

          <!--mybatis 逆向生成插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.2</version>
                    </dependency>
                </dependencies>
            </plugin>

b. 配置文件 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"/>
    <classPathEntry location="${jdbc_driverLocation}"/> <!--指定特定數據庫的jdbc驅動jar包的位置-->

    <context id="default" targetRuntime="MyBatis3">
        <!-- optional,旨在創建class時,對註釋進行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--jdbc的數據庫連接 -->
        <jdbcConnection
                driverClass="${jdbc_driverClass}"
                connectionURL="${jdbc_url}"
                userId="${jdbc_user}"
                password="${jdbc_pwd}">
        </jdbcConnection>

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

        <!-- Model模型生成器,用來生成含有主鍵key的類,記錄類 以及查詢Example類
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在該項目下所在的路徑
        -->
        <javaModelGenerator targetPackage="com.rambo.sdm.dao.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.rambo.sdm.dao.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 客戶端代碼,生成易於使用的針對Model對象和XML配置文件 的代碼
                type="ANNOTATEDMAPPER",生成Java Model 和基於註解的Mapper對象
                type="MIXEDMAPPER",生成基於註解的Java Model 和相應的Mapper對象
                type="XMLMAPPER",生成SQLMap XML文件和獨立的Mapper接口
        -->
        <javaClientGenerator targetPackage="com.rambo.sdm.dao.inter" targetProject="src/main/java" type="XMLMAPPER">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <table tableName="user" domainObjectName="UserPO">
            <generatedKey column="uuid" sqlStatement="SELECT REPLACE(UUID(),'-','') UUID FROM DUAL"/>
        </table>
    </context>
</generatorConfiguration>

c. 數據庫配置文件 jdbc.properties

jdbc_driverLocation=D:\\Program Files\\Repository\\mysql\\mysql-connector-java\\5.1.38\\mysql-connector-java-5.1.38.jar
jdbc_driverClass=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/db_test?useUnicode=true&amp;characterEncoding=utf-8
jdbc_user=root
jdbc_pwd=123456
validationQuery = select 1

d. 配置插件啓動項

2.項目實戰

User類就是普通的實體類,定義了數據庫對應的字段,以及set/get方法

Mybatis 引入了 Example 類,用來封裝數據庫查詢條件。

a. 比如在一個項目 我們要刪除某個小組下某個用戶的信息

    public int deleteUserApplyInfo(long user_id,long team_id){
        StudyTeamUserApplyInfoExample ue = new StudyTeamUserApplyInfoExample();
        ue.createCriteria().andUserIdEqualTo(new BigDecimal(user_id)).andTeamIdEqualTo(new BigDecimal(team_id));
        return studyTeamUserApplyInfoDAO.deleteByExample(ue);
    }

b. 根據小組ID(非主鍵 更新小組信息)

   public int updateStudyTeamInfo(StudyTeamInfo st){
        StudyTeamInfoExample ste = new StudyTeamInfoExample();
        ste.createCriteria().andTeamIdEqualTo(st.getTeamId());
        return studyTeamInfoDAO.updateByExampleSelective(st,ste);
    }

c. 各種查詢

(1)模糊查詢並且排序

public List<StudyTeamInfo> getStudyTeamInfoByName(String team_name){
        StudyTeamInfoExample se = new StudyTeamInfoExample();
        se.createCriteria().andTeamNameLike("%"+team_name+"%").andEnableEqualTo((short)1);
        se.setOrderByClause("team_score desc");
        List<StudyTeamInfo> ls = studyTeamInfoDAO.selectByExample(se);
        if(ls!=null&&ls.size()>0){
            return ls;
        }
        return null;
    }

(2)大於等於某個分數 並且小於某個分數的查詢

public StudyTeamLevel getStudyTeamLevel(long score){
        StudyTeamLevelExample le = new StudyTeamLevelExample();
        le.createCriteria().andNeedScoreLessThanOrEqualTo(score).andUpScoreGreaterThan(score);
        List<StudyTeamLevel> ls = studyTeamLevelDAO.selectByExample(le);
        if(ls!=null&&ls.size()>0){
            return ls.get(0);



歡迎加入我的知識星球,一起探討架構,交流源碼。加入方式,長按下方二維碼噢

已在知識星球更新源碼解析如下:

最近更新《芋道 SpringBoot 2.X 入門》系列,已經 20 餘篇,覆蓋了 MyBatis、Redis、MongoDB、ES、分庫分表、讀寫分離、SpringMVC、Webflux、權限、WebSocket、Dubbo、RabbitMQ、RocketMQ、Kafka、性能測試等等內容。

提供近 3W 行代碼的 SpringBoot 示例,以及超 4W 行代碼的電商微服務項目。

獲取方式:點“在看”,關注公衆號並回復 666 領取,更多內容陸續奉上。

兄弟,一口,點個????

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