SpringBoot集成Mybatis Generator自動生成MySQL訪問相關(guān)文件

在本地MySQL數(shù)據(jù)庫中創(chuàng)建了一個air_conditioner數(shù)據(jù)庫钞艇,只有一個devices表,這個表包含三個字段:device_id私沮、type始赎、position,本文將嘗試訪問這個數(shù)據(jù)庫仔燕。創(chuàng)建數(shù)據(jù)庫的腳本放在文末給出的git中了造垛。

1、pom文件加入mybatis依賴

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

2晰搀、pom文件加入mybatis generator插件配置

            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.35</version>
                    </dependency>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.2</version>
                    </dependency>
                </dependencies>
            </plugin>

3五辽、編寫配置文件generatorConfig.xml

這個文件定義了mybatis generator如何生成model、dao外恕、mapper杆逗,詳見官方文檔。把這個文件存放在步驟2中指定的位置:src/main/resources/mybatis-generator/

<?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="mybatis-generator/mybatisGeneratorinit.properties"/>
    <!--classPathEntry:數(shù)據(jù)庫的JDBC驅(qū)動,換成你自己的驅(qū)動位置 可選 -->
    <!--<classPathEntry location="D:\generator_mybatis\mysql-connector-java-5.1.24-bin.jar" /> -->

    <!-- 一個數(shù)據(jù)庫一個context -->
    <!--defaultModelType="flat" 大數(shù)據(jù)字段鳞疲,不分表 -->
    <context id="MysqlTables" targetRuntime="MyBatis3" defaultModelType="flat">
        <property name="autoDelimitKeywords" value="true" />
        <property name="beginningDelimiter" value="`" />
        <property name="endingDelimiter" value="`" />
        <property name="javaFileEncoding" value="utf-8" />
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />

        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />

        <!-- 注釋 -->
        <commentGenerator >
            <property name="suppressAllComments" value="false"/><!-- 是否取消注釋 -->
            <property name="suppressDate" value="true" /> <!-- 是否生成注釋代時間戳-->
        </commentGenerator>

        <!-- jdbc連接 -->
        <jdbcConnection driverClass="${jdbc_driver}" connectionURL="${jdbc_url}" userId="${jdbc_user}" password="${jdbc_password}" />
        <!-- 類型轉(zhuǎn)換 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal罪郊, false可自動轉(zhuǎn)化以下類型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成實體類地址 -->
        <javaModelGenerator targetPackage="com.quiterr.model" targetProject="${project}" >
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成mapxml文件 -->
        <sqlMapGenerator targetPackage="mappers" targetProject="${resources}" >
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- 生成mapxml對應client,也就是接口dao -->
        <javaClientGenerator targetPackage="com.quiterr.dao" targetProject="${project}" type="XMLMAPPER" >
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <table tableName="devices" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
            <property name="useActualColumnNames" value="false" />
            <generatedKey column="id" sqlStatement="Mysql" identity="true" />
        </table>

    </context>
</generatorConfiguration>

4尚洽、編寫mybatisGeneratorinit.properties

這個文件保存了一些generatorConfig.xml會用到的配置信息悔橄,比如項目的目錄、數(shù)據(jù)庫的連接信息腺毫,這些信息也可以直接放在generatorConfig.xml中癣疟,但這樣可讀性差一些。

#Mybatis Generator configuration
project =src/main/java
resources=src/main/resources
jdbc_driver =com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/air_conditioner
jdbc_user=root
jdbc_password=123456

5潮酒、生成dao睛挚、model、mapper文件

在數(shù)據(jù)庫建好之后急黎,在編寫業(yè)務代碼之前扎狱,就該生成這些文件了侧到,在maven的生命周期里似乎沒有一個合適的階段用來執(zhí)行這個操作。其實只需要在CMD中運行一行命令即可:
call mvn mybatis-generator:generate -e

6委乌、配置dao床牧、mapper的路徑

a荣回、配置dao的路徑
可以在生成的每個dao文件里添加@mapper注解遭贸,如:

@Mapper
public interface DevicesMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table devices
     *
     * @mbggenerated
     */
    int countByExample(DevicesExample example);
//后邊的代碼省略

也可以在App類添加@MapperScan注解,如:

@SpringBootApplication
@EnableScheduling
@MapperScan("com.quiterr.dao")
@EnableConfigurationProperties({AirConditionerSettings.class})
public class App {

    public static void main(String args[]){
        SpringApplication.run(App.class);
    }
}

b心软、配置mapper的路徑
在application.properties里加一行:
mybatis.mapper-locations=classpath:mappers/*.xml
ps:model的路徑不用配置壕吹,在mapper文件里面已有

7、訪問數(shù)據(jù)庫

在model目錄下删铃,mybatis generator為每一個表生成了一個example文件耳贬,通過這個文件提供了一種“面向?qū)ο蟆钡臄?shù)據(jù)庫查詢,總之不用自己寫sql語句了猎唁。

//mybatis generator生成的example文件
public class DevicesExample {
    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table devices
     *
     * @mbggenerated
     */
    protected String orderByClause;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table devices
     *
     * @mbggenerated
     */
    protected boolean distinct;
//后面的代碼省略

要查詢數(shù)據(jù)庫咒劲,首先,注入dao:

@Autowired
DevicesMapper devicesMapper;

然后像這樣:

        //從數(shù)據(jù)庫查詢各類設備的數(shù)量
        String pos="機房";
        DevicesExample devicesExample = new DevicesExample();
        DevicesExample.Criteria criteria = devicesExample.createCriteria();
        criteria.andPositionEqualTo(pos);
        List<Devices> deviceList = devicesMapper.selectByExample(devicesExample);

本文源碼:https://github.com/quiterr/mybatis-generator-test.git
官方文檔:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末诫隅,一起剝皮案震驚了整個濱河市腐魂,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌逐纬,老刑警劉巖蛔屹,帶你破解...
    沈念sama閱讀 222,378評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異豁生,居然都是意外死亡兔毒,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,970評論 3 399
  • 文/潘曉璐 我一進店門甸箱,熙熙樓的掌柜王于貴愁眉苦臉地迎上來育叁,“玉大人,你說我怎么就攤上這事芍殖『浪裕” “怎么了?”我有些...
    開封第一講書人閱讀 168,983評論 0 362
  • 文/不壞的土叔 我叫張陵围小,是天一觀的道長昵骤。 經(jīng)常有香客問我,道長肯适,這世上最難降的妖魔是什么变秦? 我笑而不...
    開封第一講書人閱讀 59,938評論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮框舔,結(jié)果婚禮上蹦玫,老公的妹妹穿的比我還像新娘赎婚。我一直安慰自己,他們只是感情好樱溉,可當我...
    茶點故事閱讀 68,955評論 6 398
  • 文/花漫 我一把揭開白布挣输。 她就那樣靜靜地躺著,像睡著了一般福贞。 火紅的嫁衣襯著肌膚如雪撩嚼。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,549評論 1 312
  • 那天挖帘,我揣著相機與錄音完丽,去河邊找鬼。 笑死拇舀,一個胖子當著我的面吹牛逻族,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播骄崩,決...
    沈念sama閱讀 41,063評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼聘鳞,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了要拂?” 一聲冷哼從身側(cè)響起抠璃,我...
    開封第一講書人閱讀 39,991評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎宇弛,沒想到半個月后鸡典,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,522評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡枪芒,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,604評論 3 342
  • 正文 我和宋清朗相戀三年彻况,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片舅踪。...
    茶點故事閱讀 40,742評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡纽甘,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出抽碌,到底是詐尸還是另有隱情悍赢,我是刑警寧澤,帶...
    沈念sama閱讀 36,413評論 5 351
  • 正文 年R本政府宣布货徙,位于F島的核電站左权,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏痴颊。R本人自食惡果不足惜赏迟,卻給世界環(huán)境...
    茶點故事閱讀 42,094評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蠢棱。 院中可真熱鬧锌杀,春花似錦甩栈、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,572評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至突想,卻和暖如春殴蹄,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背蒿柳。 一陣腳步聲響...
    開封第一講書人閱讀 33,671評論 1 274
  • 我被黑心中介騙來泰國打工饶套, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人垒探。 一個月前我還...
    沈念sama閱讀 49,159評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像怠李,于是被迫代替她去往敵國和親圾叼。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,747評論 2 361

推薦閱讀更多精彩內(nèi)容