SpringBoot+MybatisPlus+Druid極速搭建項(xiàng)目原型

前言

聽說你又有新需求了酣溃?
什么弥喉?又是對(duì)某些表的增刪改查蓖谢?
什么年缎?還要從數(shù)據(jù)庫一直寫到dao層翰意?還要配置mapper.xml文件堕汞?完事兒之后還要寫service層玛追、controller層披诗?
什么甲献?遇到條件查詢還要寫dao層和xml文件中的sql語句宰缤?
什么?有新需求了竟纳,要加分頁撵溃?使用pageHelper文件?
搬磚的活兒怎么配得上你一代碼神的氣質(zhì)锥累?
少年缘挑,看你筋骨奇特,配上mybatis plus必能擺脫搬磚的苦惱桶略。一掃以上所有問題语淘!
廢話不多說,項(xiàng)目git地址 https://github.com/KouLouYiMaSi/mybatis-plus.git

Mybatis Plus優(yōu)勢(shì)

  • 可以提供代碼層面的條件查詢
  • 可以快速生成代碼
  • 集成了分頁插件

SpringBoot整合實(shí)戰(zhàn)

step1
配置maven依賴际歼,最重要的是上面的第一個(gè)和第二個(gè)惶翻,第二個(gè)負(fù)責(zé)生成代碼做模板

    <dependencies>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.16</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

step2
配置application.xml文件,有了這個(gè)配置就不用寫druid的配置類了,這是新版Druid的糖

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
    username: username
    password: password
    druid:
      # 初始化大小鹅心,最小吕粗,最大
      initial-size: 5
      min-idle: 5
      maxActive: 20
      # 配置獲取連接等待超時(shí)的時(shí)間
      maxWait: 60000
      # 配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接旭愧,單位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一個(gè)連接在池中最小生存的時(shí)間颅筋,單位是毫秒
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 打開PSCache宙暇,并且指定每個(gè)連接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      # 配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計(jì)议泵,'wall'用于防火墻
      filters: stat,wall
      # 通過connectProperties屬性來打開mergeSql功能占贫;慢SQL記錄
      connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
      # 配置DruidStatFilter
      web-stat-filter:
        enabled: true
        url-pattern: "/*"
        exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
      # 配置DruidStatViewServlet
      stat-view-servlet:
        url-pattern: "/druid/*"
        # IP白名單(沒有配置或者為空,則允許所有訪問)
        allow: 127.0.0.1,192.168.163.1
        # IP黑名單 (存在共同時(shí)先口,deny優(yōu)先于allow)
        deny: 192.168.1.73
        #  禁用HTML頁面上的“Reset All”功能
        reset-enable: false
        # 登錄名
        login-username: admin
        # 登錄密碼
        login-password: 123456
mybatis-plus:
  mapper-locations: classpath:/com/example/demo/mapper/*/*.xml
  typeAliasesPackage: com.example.demo.entity
  global-config:
    id-type: 2
    field-strategy: 2
    db-column-underline: true
    refresh-mapper: true
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
server:
  port: 8082

step3
配置生成代碼的類和分頁插件配置類

package com.example.demo.config;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

/**
 * 小混蛋
 */
public class CodeGenerator {

    public static final String DB_URL = "jdbc:mysql://localhost:3306/hawkeye?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true";
    public static final String USER_NAME = "用戶名";
    public static final String PASSWORD = "密碼";
    public static final String DRIVER = "com.mysql.jdbc.Driver";
    public static final String AUTHOR = "作者名稱";
    //生成的文件輸出到哪個(gè)目錄
    public static final String OUTPUT_FILE = "D:\\codeGen";
    //包名型奥,會(huì)按照com/example/demo這種形式生成類
    public static final String PACKAGE = "com.example.demo";
    //TODO 更多配置請(qǐng)參考http://mp.baomidou.com/#/generate-code

    public void generateByTables(boolean serviceNameStartWithI, String... tableNames) {
        GlobalConfig config = new GlobalConfig();
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL)
                .setUrl(DB_URL)
                .setUsername(USER_NAME)
                .setPassword(PASSWORD)
                .setDriverName(DRIVER);
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
                .setCapitalMode(true)
                .setEntityLombokModel(false)
                .setDbColumnUnderline(true)
                .setNaming(NamingStrategy.underline_to_camel)
                .setInclude(tableNames);//修改替換成你需要的表名,多個(gè)表名傳數(shù)組
        config.setActiveRecord(false)
                .setAuthor(AUTHOR)
                .setOutputDir(OUTPUT_FILE)
                .setFileOverride(true);
        if (!serviceNameStartWithI) {
            config.setServiceName("%sService");
        }
        new AutoGenerator().setGlobalConfig(config)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(
                        new PackageConfig()
                                .setParent(PACKAGE)
                                .setController("controller")
                                .setEntity("entity")
                ).execute();
    }
}
package com.example.demo.config;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.example.demo.mapper")
public class MybatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

step4
寫一個(gè)junit test類碉京,用于生成代碼

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
    @Test
    public void contextLoads() {
        CodeGenerator gse = new CodeGenerator();
        //要給那些表生成
        gse.generateByTables(false,"tb_user", "tb_role","tb_permission","tb_user_role","tb_role_permission");
    }
}

step5
執(zhí)行junit test類厢汹,生成代碼之后就可以用了

mybatis-plus用法

  • mapper層和service層基本上啥也不用動(dòng),當(dāng)然收夸,如果你需要其他邏輯可以在service層添加方法
  • controller直接注入service直接調(diào)用就ok 了
  • 條件查詢用EntityWrapper坑匠,輸入點(diǎn)之后ide會(huì)給你你想要的提示
  • 分頁查詢只需要selectPage方法即可,就是這么簡單
@Controller
@RequestMapping("/tbUser")
public class TbUserController {
    @Autowired
    private TbUserService tbUserService;

    @RequestMapping("/all")
    @ResponseBody
    public List<TbUser> getAll(){
        return tbUserService.selectList(new EntityWrapper<TbUser>());
    }
    @RequestMapping("/allbypage")
    @ResponseBody
    public Page<TbUser> getAllByPage(Integer pageNum,Integer pageSize){
        return tbUserService.selectPage(new Page<TbUser>(pageNum,pageSize));
    }
    @RequestMapping("/insert")
    @ResponseBody
    public boolean insert(TbUser tbUser){
        return tbUserService.insert(tbUser);
    }
    @RequestMapping("/insert")
    @ResponseBody
    public boolean delete(Integer id){
        return tbUserService.deleteById(id);
    }

    @RequestMapping("/insert")
    @ResponseBody
    public List<TbUser> getUserById(Integer uid){
        return tbUserService.selectList(
                new EntityWrapper<TbUser>()
                .eq("uid",uid)
        );
    }
}

總結(jié)

以后再做管理系統(tǒng)建完表就直接生成卧惜,反正一般都是給內(nèi)部人用厘灼,后期涉及到優(yōu)化也就是加索引什么的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末咽瓷,一起剝皮案震驚了整個(gè)濱河市设凹,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌茅姜,老刑警劉巖闪朱,帶你破解...
    沈念sama閱讀 218,204評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異钻洒,居然都是意外死亡奋姿,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門素标,熙熙樓的掌柜王于貴愁眉苦臉地迎上來称诗,“玉大人,你說我怎么就攤上這事头遭≡⒚猓” “怎么了?”我有些...
    開封第一講書人閱讀 164,548評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵计维,是天一觀的道長袜香。 經(jīng)常有香客問我,道長鲫惶,這世上最難降的妖魔是什么蜈首? 我笑而不...
    開封第一講書人閱讀 58,657評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上疾就,老公的妹妹穿的比我還像新娘澜术。我一直安慰自己艺蝴,他們只是感情好猬腰,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著猜敢,像睡著了一般姑荷。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上缩擂,一...
    開封第一講書人閱讀 51,554評(píng)論 1 305
  • 那天鼠冕,我揣著相機(jī)與錄音,去河邊找鬼胯盯。 笑死懈费,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的博脑。 我是一名探鬼主播憎乙,決...
    沈念sama閱讀 40,302評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼叉趣!你這毒婦竟也來了泞边?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,216評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤疗杉,失蹤者是張志新(化名)和其女友劉穎阵谚,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體烟具,經(jīng)...
    沈念sama閱讀 45,661評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡梢什,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了朝聋。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片嗡午。...
    茶點(diǎn)故事閱讀 39,977評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖玖翅,靈堂內(nèi)的尸體忽然破棺而出翼馆,到底是詐尸還是另有隱情,我是刑警寧澤金度,帶...
    沈念sama閱讀 35,697評(píng)論 5 347
  • 正文 年R本政府宣布应媚,位于F島的核電站,受9級(jí)特大地震影響猜极,放射性物質(zhì)發(fā)生泄漏中姜。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望丢胚。 院中可真熱鬧翩瓜,春花似錦、人聲如沸携龟。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽峡蟋。三九已至坟桅,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蕊蝗,已是汗流浹背仅乓。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評(píng)論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蓬戚,地道東北人夸楣。 一個(gè)月前我還...
    沈念sama閱讀 48,138評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像子漩,于是被迫代替她去往敵國和親豫喧。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評(píng)論 2 355

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

  • 1. 簡介 1.1 什么是 MyBatis 痛单? MyBatis 是支持定制化 SQL嘿棘、存儲(chǔ)過程以及高級(jí)映射的優(yōu)秀的...
    笨鳥慢飛閱讀 5,520評(píng)論 0 4
  • 在開發(fā)中鸟妙,編碼我們有分層架構(gòu)、設(shè)計(jì)模式做為套路來高效開發(fā)挥吵,但你也知道編碼不是開發(fā)的全部重父,一個(gè)完全的開發(fā)流程用面向?qū)?..
    stay4it閱讀 8,355評(píng)論 30 215
  • 序 本文主要研究一下rocketmq的RemotingException RemotingException or...
    go4it閱讀 8,870評(píng)論 0 1
  • 冰雪已消融, 春意催楊柳忽匈。 梅花悄悄傳喜訊房午, 不覺冬已走。 身在紅塵中丹允, 歲月猶長久郭厌, 人生路上莫等閑, 有夢(mèng)就追求雕蔽。
    ZHOU春雨閱讀 288評(píng)論 3 10