最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot快速整合Mybatis、MybatisPlus(代碼生成器)實(shí)現(xiàn)數(shù)據(jù)庫(kù)訪(fǎng)問(wèn)功能

 更新時(shí)間:2021年04月12日 11:10:05   作者:JavaHungry  
這篇文章主要介紹了SpringBoot快速整合Mybatis、MybatisPlus(代碼生成器)實(shí)現(xiàn)數(shù)據(jù)庫(kù)訪(fǎng)問(wèn)功能,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

 1. 創(chuàng)建SpringBoot項(xiàng)目

在這里插入圖片描述

1.1 引入依賴(lài)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
    </parent>

    <groupId>com.gcl</groupId>
    <artifactId>vue_day03_admin</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!--spring-web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>

        <!--mybatis-plus代碼生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>


        <!--mysql驅(qū)動(dòng)-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <!--數(shù)據(jù)庫(kù)連接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.21</version>
        </dependency>


        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--測(cè)試-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--lang3工具類(lèi)-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.10</version>
        </dependency>
    </dependencies>

    <!-- maven插件,可以將應(yīng)用打包成一個(gè)可執(zhí)行的jar包;-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1.2 編寫(xiě)配置文件

application.yml

server:
  port: 8088

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://192.168.0.131:3306/vue_day03?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password: Root@123456

mybatis-plus:
  type-aliases-package: com.gcl.entity
  configuration:
    map-underscore-to-camel-case: true
    use-generated-keys: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath:com/gcl/mapper/*Mapper.xml

logging:
  level:
    com.demo.mapper: debug

2. 編寫(xiě)MybatisPlus代碼生成工具類(lèi)

在這里插入圖片描述

2.1 編寫(xiě)代碼生成工具類(lèi)

CodeGenerator.java

package com.gcl.utils;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// 執(zhí)行 main 方法控制臺(tái)輸入模塊表名回車(chē)自動(dòng)生成對(duì)應(yīng)項(xiàng)目目錄中
public class CodeGenerator {

    /**
     * <p>
     * 讀取控制臺(tái)內(nèi)容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("請(qǐng)輸入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("請(qǐng)輸入正確的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代碼生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/vue_day03_admin/src/main/java");
        gc.setAuthor("gcl");
        // 是否打開(kāi)輸出目錄,默認(rèn)true
        gc.setOpen(false);
        // 開(kāi)啟 ActiveRecord 模式,默認(rèn)false
        gc.setActiveRecord(true);
        // 是否覆蓋已有文件
        gc.setFileOverride(true);
        // XML 開(kāi)啟 BaseResultMap
        gc.setBaseResultMap(true);
        // XML 開(kāi)啟 baseColumnList
        gc.setBaseColumnList(true);

        // 自定義文件命名,注意 %s 會(huì)自動(dòng)填充表實(shí)體屬性!
        // gc.setMapperName("%sDao");
        // gc.setXmlName("%sMapper");
         gc.setServiceName("%sService");
        // gc.setServiceImplName("%sServiceDiy");
        // gc.setControllerName("%sAction");

        mpg.setGlobalConfig(gc);

        // 數(shù)據(jù)源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);

        dsc.setUrl("jdbc:mysql://192.168.0.131:3306/vue_day03?useUnicode=true&useSSL=false&characterEncoding=utf8");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("Root@123456");
        dsc.setTypeConvert(new MySqlTypeConvert(){
            // 自定義數(shù)據(jù)庫(kù)表字段類(lèi)型轉(zhuǎn)換【可選】
            @Override
            public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                System.out.println("轉(zhuǎn)換類(lèi)型:" + fieldType);
                // 注意!!processTypeConvert 存在默認(rèn)類(lèi)型轉(zhuǎn)換,如果不是你要的效果請(qǐng)自定義返回、非如下直接返回。
                return super.processTypeConvert(globalConfig, fieldType);
            }
        });
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();

        // com.demo.user
        pc.setParent("com");
//        pc.setModuleName("user");
        pc.setModuleName(scanner("模塊名"));
        mpg.setPackageInfo(pc);

        // 自定義配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // TODO
            }
        };

        mpg.setCfg(cfg);

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";

        // 自定義輸出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定義配置會(huì)被優(yōu)先輸出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸出文件名 , 如果你 Entity 設(shè)置了前后綴、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化??!
                return projectPath + "/vue_day03_admin/src/main/resources/com/gcl/mapper"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 此處可以修改為您的表前綴
        strategy.setTablePrefix(new String[] { "tb_", "tsys_","t_" });
        // 表名生成策略
        strategy.setNaming(NamingStrategy.underline_to_camel);
        // 需要生成的表
        strategy.setInclude(scanner("表名,多個(gè)英文逗號(hào)分割").split(","));
//        strategy.setInclude(new String[] { "tb_user" });
        strategy.setEntityBuilderModel(true);

        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

2.2 創(chuàng)建數(shù)據(jù)庫(kù)及表

創(chuàng)表語(yǔ)句

CREATE TABLE `t_user` (
  `id` int(60) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `username` varchar(255) DEFAULT NULL COMMENT '姓名',
  `salary` double(7,2) DEFAULT NULL COMMENT '薪水',
  `age` int(11) DEFAULT NULL,
  `desc` varchar(255) DEFAULT NULL COMMENT '描述',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

2.3 測(cè)試代碼生成器

執(zhí)行CodeGenerator類(lèi)中的main方法

在這里插入圖片描述

在這里插入圖片描述

執(zhí)行代碼生成器之后的結(jié)果

在這里插入圖片描述

3. 添加分頁(yè)配置

在這里插入圖片描述

MyBatisPlusConfig.java

package com.gcl.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName MyBatisPlusConfig
 * @Description TODO
 * @Author gcl
 * @Date 2021-03-18 8:36
 **/
@Configuration
public class MyBatisPlusConfig {
    /**
     * mybatis-plus 分頁(yè)插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }
}

4. 測(cè)試訪(fǎng)問(wèn)接口從數(shù)據(jù)庫(kù)中獲取數(shù)據(jù)(帶分頁(yè))

4.1 數(shù)據(jù)庫(kù)中添加5條數(shù)據(jù)

INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('1', '張三', '2000.00', '23', '95年05月生');
INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('2', '李四', '3000.00', '24', '96年06年生');
INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('3', '王五', '4000.00', '25', '07年07年生');
INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('4', '趙六', '5000.00', '26', '08年08月生');
INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('5', '田七', '6000.00', '27', '09年09月生');

4.2 編寫(xiě)查詢(xún)方法

package com.gcl.controller;

import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gcl.entity.User;
import com.gcl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gcl
 * @since 2021-04-10
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     *
     * @param pageNo 當(dāng)前頁(yè)
     * @param pageSize 每頁(yè)顯示的記錄數(shù)
     * @return
     */
    @GetMapping
    public List<User> findList(int pageNo,int pageSize){


        //創(chuàng)建查詢(xún)條件封裝器
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        
        Page<User> page = new Page<>(pageNo, pageSize);

        IPage<User> iPage = userService.page(page, wrapper);

        List<User> records = iPage.getRecords();

        return records;

    }

}

4.3 用postman工具測(cè)試分頁(yè)

先測(cè)試第一頁(yè)每頁(yè)顯示3條記錄

在這里插入圖片描述

查看第二頁(yè)的數(shù)據(jù)

在這里插入圖片描述

到此這篇關(guān)于SpringBoot快速整合Mybatis、MybatisPlus(代碼生成器)實(shí)現(xiàn)數(shù)據(jù)庫(kù)訪(fǎng)問(wèn)功能的文章就介紹到這了,更多相關(guān)SpringBoot實(shí)現(xiàn)數(shù)據(jù)庫(kù)訪(fǎng)問(wèn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot中@ConditionalOnProperty的使用及作用詳解

    SpringBoot中@ConditionalOnProperty的使用及作用詳解

    這篇文章主要介紹了SpringBoot中@ConditionalOnProperty的使用及作用詳解,@ConditionalOnProperty通過(guò)讀取本地配置文件中的值來(lái)判斷 某些 Bean 或者 配置類(lèi) 是否加入spring 中,需要的朋友可以參考下
    2024-01-01
  • 部署Nacos的源碼環(huán)境搭建過(guò)程

    部署Nacos的源碼環(huán)境搭建過(guò)程

    這篇文章主要為大家介紹了部署Nacos的源碼環(huán)境搭建過(guò)程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-02-02
  • java統(tǒng)計(jì)字符串單詞個(gè)數(shù)的方法解析

    java統(tǒng)計(jì)字符串單詞個(gè)數(shù)的方法解析

    在一些項(xiàng)目中可能需要對(duì)一段字符串中的單詞進(jìn)行統(tǒng)計(jì),本文在這里分享了一個(gè)簡(jiǎn)單的demo,有需要的朋友可以拿去看一下
    2017-01-01
  • Java常用占位符方法簡(jiǎn)單代碼實(shí)例

    Java常用占位符方法簡(jiǎn)單代碼實(shí)例

    占位符是Java中常用的技術(shù),用于在字符串中插入變量值或動(dòng)態(tài)生成字符串,這篇文章主要給大家介紹了關(guān)于Java常用占位符方法的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友可以參考下
    2024-01-01
  • Java SpringBoot攔截器詳解

    Java SpringBoot攔截器詳解

    這篇文章主要介紹了Java SpringBoot攔截器的使用方法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2021-10-10
  • Spring Boot2.0 @ConfigurationProperties使用詳解

    Spring Boot2.0 @ConfigurationProperties使用詳解

    這篇文章主要介紹了Spring Boot2.0 @ConfigurationProperties使用詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-11-11
  • SpringBoot使用Cache集成Redis做緩存的保姆級(jí)教程

    SpringBoot使用Cache集成Redis做緩存的保姆級(jí)教程

    Spring Cache是Spring框架提供的一個(gè)緩存抽象層,它簡(jiǎn)化了緩存的使用和管理,Spring Cache默認(rèn)使用服務(wù)器內(nèi)存,并無(wú)法控制緩存時(shí)長(zhǎng),查找緩存中的數(shù)據(jù)比較麻煩,本文已常用的Redis作為緩存中間件作為示例,詳細(xì)講解項(xiàng)目中如何使用Cache提高系統(tǒng)性能,需要的朋友可以參考下
    2025-01-01
  • SpringBoot整合Spring?Data?JPA的詳細(xì)方法

    SpringBoot整合Spring?Data?JPA的詳細(xì)方法

    JPA全稱(chēng)為Java Persistence API(Java持久層API),是一個(gè)基于ORM的標(biāo)準(zhǔn)規(guī)范,在這個(gè)規(guī)范中,JPA只定義標(biāo)準(zhǔn)規(guī)則,不提供實(shí)現(xiàn),本文重點(diǎn)給大家介紹SpringBoot整合Spring?Data?JPA的相關(guān)知識(shí),感興趣的朋友一起看看吧
    2022-02-02
  • Java中的==使用方法詳解

    Java中的==使用方法詳解

    這篇文章主要給大家介紹了關(guān)于Java中的==使用方法的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-09-09
  • 關(guān)于Java Guava ImmutableMap不可變集合源碼分析

    關(guān)于Java Guava ImmutableMap不可變集合源碼分析

    這篇文章主要介紹Java Guava不可變集合ImmutableMap的源碼分析的相關(guān)資料,需要的朋友可以參考下面具體的文章內(nèi)容
    2021-09-09

最新評(píng)論

抚顺县| 丹江口市| 渭源县| 肥乡县| 林州市| 醴陵市| 巨鹿县| 恭城| 迭部县| 巧家县| 安吉县| 阜平县| 广南县| 莆田市| 柳林县| 含山县| 福海县| 砚山县| 西青区| 渑池县| 黄陵县| 镇赉县| 淄博市| 托克逊县| 长丰县| 芜湖市| 泸西县| 湟源县| 陕西省| 体育| 桂林市| 惠来县| 云安县| 三门县| 青阳县| 定兴县| 买车| 固安县| 霍林郭勒市| 九龙坡区| 潢川县|