検索
ホームページJava&#&チュートリアルSpringBoot が mybatis+mybatis-plus を統合する方法

準備作業

1. 以下のデータテーブルを準備します

CREATE TABLE `student` (
  `id` varchar(32) NOT NULL,
  `gender` varchar(32) DEFAULT NULL,
  `age` int(12) DEFAULT NULL,
  `nick_name` varchar(32) DEFAULT NULL,
  `name` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. いくつかのテストデータを挿入します

SpringBoot が mybatis+mybatis-plus を統合する方法

統合手順

プロジェクトの完全なパッケージ構造を図に示します

SpringBoot が mybatis+mybatis-plus を統合する方法

#1. Maven の依存関係をインポートします

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <mysql-connector-java.version>8.0.11</mysql-connector-java.version>
        <commons-lang3.version>3.7</commons-lang3.version>
        <fastjson.version>1.2.47</fastjson.version>
        <mybatis-plus-boot-starter.version>3.3.0</mybatis-plus-boot-starter.version>
        <mybatis-plus-generator.version>3.3.0</mybatis-plus-generator.version>
        <druid.version>1.1.14</druid.version>
        <lombok.version>1.18.0</lombok.version>
        <dubbo-spring-boot-starter.version>2.0.0</dubbo-spring-boot-starter.version>
        <swagger.version>2.9.2</swagger.version>
        <swagger-bootstrap-ui.version>1.9.6</swagger-bootstrap-ui.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <!--mysql依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-java.version}</version>
        </dependency>
 
        <!--阿里巴巴fastjosn依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
 
        <!--阿里巴巴数据库连接池依赖-->
        <!-- Druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.version}</version>
        </dependency>
 
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
 
        <!-- MyBatis增强工具-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus-boot-starter.version}</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>${mybatis-plus-generator.version}</version>
        </dependency>
 
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>
 
        <!--swagger-ui-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
 
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>
 
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>${swagger-bootstrap-ui.version}</version>
        </dependency>
 
    </dependencies>

2. 設定ファイルのアプリケーション.yml

server:
  port: 8083
logging:
  config: classpath:logback-spring.xml  #日志
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://IP:3306/school?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
    username: root
    password: root
    druid:
      max-active: 100
      initial-size: 10
      max-wait: 60000
      min-idle: 5
  #设置单个文件最大上传大小
  servlet:
    multipart:
      max-file-size: 20MB
mybatis-plus:
  mapper-locations: classpath*:mapper/*.xml
  global-config:
    db-column-underline: true  #开启驼峰转换
    db-config:
      id-type: uuid
      field-strategy: not_null
    refresh: true
  configuration:
    map-underscore-to-camel-case: true
    #log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql语句便于调试

3. 後でインターフェイスのデバッグを容易にするために、swagger 構成を追加します

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
/**
 * swagger文档,项目启动后,浏览器访问:http://localhost:8083/swagger-ui.html
 */
@Configuration
@EnableSwagger2
public class ApiSwagger2 {
 
    @Bean
    public Docket createRestBmbsApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("users")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.congge.controller"))
                .paths(PathSelectors.any())
                .build();
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("后端相关API")
                .version("1.0")
                .build();
    }
 
}

4. エンティティ クラス

import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
 
@Data
public class Student {
 
    @TableField("id")
    private String id;
 
    @TableField("name")
    private String name;
 
    @TableField("gender")
    private String gender;
 
    @TableField("age")
    private int age;
 
    @TableField("nick_name")
    private String nickName;
 
}

5. Dao インターフェイス、メソッドを追加しますすべてのデータをクエリするには

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.congge.entity.Student;
import org.apache.ibatis.annotations.Mapper;
 
import java.util.List;
 
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
 
    List<Student> queryAll();
 
}

6. Mybatis レイヤー、SQL ファイルを書き込みます##

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.congge.dao.StudentMapper">
 
    <select id="queryAll" resultType="com.congge.entity.Student">
		select * from student
	</select>
 
</mapper>

7. ビジネス実装クラス

このビジネス実装では、mybatis メソッドと mybatis を使用できます。 - プラスの方法、具体的に使用する場合は自分のニーズに基づいて選択します;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.congge.dao.StudentMapper;
import com.congge.entity.Student;
import com.congge.service.StudentService;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import java.util.List;
 
@Service
public class StudentServiceImpl implements StudentService {
 
    @Resource
    private StudentMapper studentMapper;
 
    @Override
    public List<Student> queryAllStudent() {
        QueryWrapper<Student> queryWrapper = new QueryWrapper();
        List<Student> students = studentMapper.selectList(queryWrapper);
        return students;
        //return studentMapper.queryAll();
    }
 
    @Override
    public List<Student> getByName(String name) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper();
        queryWrapper.like("name",name);
        return studentMapper.selectList(queryWrapper);
    }
 
    public Student getById(String id) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper();
        queryWrapper.like("id",id);
        return studentMapper.selectOne(queryWrapper);
    }
}

8. テスト インターフェイスを追加します

@RestController
public class StudentController {
 
    @Autowired
    private StudentService studentService;
 
    @GetMapping("/getAll")
    public List<Student> getAll(){
        return studentService.queryAllStudent();
    }
 
    @GetMapping("/getByName")
    public List<Student> getByName(@RequestParam String name){
        return studentService.getByName(name);
    }
 
    @GetMapping("/getById")
    public Student getById(@RequestParam String id){
        return studentService.getById(id);
    }
}

9. クラスを開始します

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class App {
 
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
 
}

次に、実行しますプロジェクトを作成してテストします。

10. 開始したら、Swagger インターフェイスを開きます

SpringBoot が mybatis+mybatis-plus を統合する方法

SpringBoot が mybatis+mybatis-plus を統合する方法

2 つをテストすることもできます。ランダムにインターフェイスを使用してテストして、すべての生徒のデータ インターフェイスを取得しましょう

SpringBoot が mybatis+mybatis-plus を統合する方法

以上がSpringBoot が mybatis+mybatis-plus を統合する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事は亿速云で複製されています。侵害がある場合は、admin@php.cn までご連絡ください。
プラットフォームの独立性は、エンタープライズレベルのJavaアプリケーションにどのように利益をもたらしますか?プラットフォームの独立性は、エンタープライズレベルのJavaアプリケーションにどのように利益をもたらしますか?May 03, 2025 am 12:23 AM

Javaは、プラットフォームの独立性により、エンタープライズレベルのアプリケーションで広く使用されています。 1)プラットフォームの独立性は、Java Virtual Machine(JVM)を介して実装されているため、Javaをサポートする任意のプラットフォームでコードを実行できます。 2)クロスプラットフォームの展開と開発プロセスを簡素化し、柔軟性とスケーラビリティを高めます。 3)ただし、パフォーマンスの違いとサードパーティライブラリの互換性に注意を払い、純粋なJavaコードやクロスプラットフォームテストの使用などのベストプラクティスを採用する必要があります。

プラットフォームの独立性を考慮して、JavaはIoT(Thingのインターネット)デバイスの開発においてどのような役割を果たしますか?プラットフォームの独立性を考慮して、JavaはIoT(Thingのインターネット)デバイスの開発においてどのような役割を果たしますか?May 03, 2025 am 12:22 AM

javaplaysasificanificantduetduetoitsplatformindepence.1)itallowscodetobewrittendunonvariousdevices.2)java'secosystemprovidesutionforiot.3)そのセキュリティフィートルセンハンス系

Javaでプラットフォーム固有の問題に遭遇したシナリオと、どのように解決したかを説明してください。Javaでプラットフォーム固有の問題に遭遇したシナリオと、どのように解決したかを説明してください。May 03, 2025 am 12:21 AM

TheSolution to HandlefilepathsaCrosswindossandlinuxinjavaistousepaths.get()fromthejava.nio.filepackage.1)usesystem.getProperty( "user.dir")およびhearterativepathtoconstructurctthefilepath.2)

開発者にとってJavaのプラットフォーム独立性の利点は何ですか?開発者にとってJavaのプラットフォーム独立性の利点は何ですか?May 03, 2025 am 12:15 AM

java'splatformentepenceissificAntiveSifcuseDeverowsDevelowSowRitecodeOdeonceantoniTONAnyPlatformwsajvm.これは「writeonce、runanywhere」(wora)adportoffers:1)クロスプラットフォームの複雑性、deploymentacrossdiferentososwithusisues; 2)re

さまざまなサーバーで実行する必要があるWebアプリケーションにJavaを使用することの利点は何ですか?さまざまなサーバーで実行する必要があるWebアプリケーションにJavaを使用することの利点は何ですか?May 03, 2025 am 12:13 AM

Javaは、クロスサーバーWebアプリケーションの開発に適しています。 1)Javaの「Write and、Run Averywhere」哲学は、JVMをサポートするあらゆるプラットフォームでコードを実行します。 2)Javaには、開発プロセスを簡素化するために、SpringやHibernateなどのツールを含む豊富なエコシステムがあります。 3)Javaは、パフォーマンスとセキュリティにおいて優れたパフォーマンスを発揮し、効率的なメモリ管理と強力なセキュリティ保証を提供します。

JVMは、Javaの「Write and、Run Anywhere」(Wora)機能にどのように貢献しますか?JVMは、Javaの「Write and、Run Anywhere」(Wora)機能にどのように貢献しますか?May 02, 2025 am 12:25 AM

JVMは、バイトコード解釈、プラットフォームに依存しないAPI、動的クラスの負荷を介してJavaのWORA機能を実装します。 2。標準API抽象オペレーティングシステムの違い。 3.クラスは、実行時に動的にロードされ、一貫性を確保します。

Javaの新しいバージョンは、プラットフォーム固有の問題にどのように対処しますか?Javaの新しいバージョンは、プラットフォーム固有の問題にどのように対処しますか?May 02, 2025 am 12:18 AM

Javaの最新バージョンは、JVMの最適化、標準的なライブラリの改善、サードパーティライブラリサポートを通じて、プラットフォーム固有の問題を効果的に解決します。 1)Java11のZGCなどのJVM最適化により、ガベージコレクションのパフォーマンスが向上します。 2)Java9のモジュールシステムなどの標準的なライブラリの改善は、プラットフォーム関連の問題を削減します。 3)サードパーティライブラリは、OpenCVなどのプラットフォーム最適化バージョンを提供します。

JVMによって実行されたバイトコード検証のプロセスを説明します。JVMによって実行されたバイトコード検証のプロセスを説明します。May 02, 2025 am 12:18 AM

JVMのバイトコード検証プロセスには、4つの重要な手順が含まれます。1)クラスファイル形式が仕様に準拠しているかどうかを確認し、2)バイトコード命令の有効性と正確性を確認し、3)データフロー分析を実行してタイプの安全性を確保し、検証の完全性とパフォーマンスのバランスをとる。これらの手順を通じて、JVMは、安全で正しいバイトコードのみが実行されることを保証し、それによりプログラムの完全性とセキュリティを保護します。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。