MyBatis-Plus & SpringBoot integrates the MyBatis-Plus book store project

Table of contents

1. MyBatis-Plus

1.1 Official website

1.2 Introduction

1.2.1 Basic concepts

1.2.2 Frame structure

1.3 Mybatis-Plus adds dependencies

2. SpringBoot integrates the MyBatis-Plus book store project

2.1 Create a new table in the database

2.1.1 Preparation for creating a new table

2.1.2 Create a new table

2.1.2.1 Open the database connection and create a new database market_tab

2.1.2.2 Create new table 1: book_tab

2.1.2.3 Create new table 2: book_publisher_tab

2.1.2.4 Create new table 3: book_type_tab

2.2 Create a new Maven project

2.3 Import dependencies in the pom.xml file

2.3.1 Import dependencies

2.3.2 Supplement: Why don’t some versions have version numbers?

2.4 Create a new project structure (package)

2.5 Create a new application.yml file and configure jdbc and mybatis-plus

2.6 Create new folders for project hierarchies

2.7 Create a new entity class entity

2.7.1 @TableName

2.7.2 @TableId

2.7.3 @TableField

2.7.4 Example of creating entity class Book

2.7.5 Supplement

2.8 The persistence layer defines the CRUD interface

2.9 service business layer

2.9.1 service interface

2.9.2 Service interface implementation

2.10 Unit testing-junit


1. MyBatis-Plus

1.1 Official website

1.2 Introduction

1.2.1 Basic concepts

Mybatis-Plus (MP for short) is an enhancement tool for Mybatis. It only enhances but does not change Mybatis. MyBatis-Plus supports all Mybatis native features, so introducing Mybatis-Plus will not affect the existing Mybatis. Frame has any impact. MyBatis enhancement toolkit to simplify CRUD operations. Inject single-table SQL operation when starting to load XML configuration, which is designed to simplify development work and improve productivity.

1.2.2 Frame structure

[Schematic diagram: mybatis-plus framework structure]

[Note] This picture is reproduced from the official website. It is recommended that you read more of the official website.

1.3 Mybatis-Plus adds dependencies

[Example: Official website adding dependency method]

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.3.1</version>
        <!-- 官网当前最新版本 -->
    </dependency>
</dependencies>

2. SpringBoot integrates the MyBatis-Plus book store project

2.1 Create a new table in the database

2.1.1 Preparation for creating a new table

[Schematic diagram: Information required for online e-commerce sales of books]

[Schematic diagram: Book information]

  • This project is an online e-commerce book sales project. You can refer to the Dangdang online book shopping mall. For now, create three new tables, namely the book information table, the publishing house table and the book type table. The specific design table information is as follows:
2.1.2 Create a new table
2.1.2.1 Open the database connection and create a new database market_tab

[Schematic diagram]

2.1.2.2 Create new table 1: book_tab

[Table 1: book_tab]

2.1.2.3 Create new table 2: book_publisher_tab

[Table 2: book_publisher_tab]

2.1.2.4 Create new table 3: book_type_tab

[Table 3: book_type_tab]

2.2 Create a new Maven project

[Schematic diagram]

2.3 Import dependencies in the pom.xml file

2.3.1 Import dependencies

[Example: pom.xml import dependencies]

<?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>

    <groupId>com.wnhz.market</groupId>
    <artifactId>woniu-market</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--  <packaging>jar</packaging>  默认是jar-->

    <!-- 第三方引入包的版本说明 -->
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!--<project.druid.version>1.2.18</project.druid.version>-->
    </properties>

    <!-- 起步依赖-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.14</version>
    </parent>

    <!-- 项目依赖 -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!--排除某些配置
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>-->
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!-- 数据库 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- 数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <!--<version>${project.druid.version}</version>-->
            <version>1.2.18</version>
        </dependency>

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

        <!--spring的单元测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <!-- 项目打包 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
2.3.2 Supplement: Why don’t some versions have version numbers?

[Q] Why do some of them not have version numbers?

[Answer] Because our starting dependency parent has a defined version number, which can be seen by clicking on it with ctrl.

2.4 Create a new project structure (package)

  • Create a new App.java file under com.wnhz.market, then add the annotation @SpringBootApplication, write the main method, and add SpringApplication.run(App.class);

[Example: Project Architecture App]

package com.wnhz.market;

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);
    }
}

2.5 Create a new application.yml file and configure jdbc and mybatis-plus

  • Create a new config folder under the resources folder, then create a new application.yml file and add the configuration

[Example: application.yml configures jdbc and mybatis-plus]

spring:
  datasource:
    druid:
      url: jdbc:mysql://192.168.41.128:3306/market_db?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
      username: root
      password: 123
      driver-class-name: com.mysql.cj.jdbc.Driver
# 注意192.168.41.128是自己的finalshell左上角地址,数据库名market_db及用户名和密码也要记得改

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

2.6 Create new folders for project hierarchies

[Schematic diagram: Project layering]

  • Layered under the project folder com.wnhz.market, create a newentity, dao, service, controllerfolder

2.7 Create a new entity class entity

2.7.1 @TableName
  • @TableName
    • Description: Table name annotation, identifying the table corresponding to the entity class
    • Where to use: Entity class

Attributes

type

Must be specified

default value

describe

value

String

no

""

Table Name

schema

String

no

""

schema

keepGlobalPrefix

boolean

no

false

Whether to keep using the global tablePrefix value (when the global tablePrefix is ​​in effect)

resultMap

String

no

""

The id of resultMap in xml (used to satisfy entity class object binding of specific types)

autoResultMap

boolean

no

false

Whether to automatically build resultMap and use it (if resultMap is set, automatic construction and injection of resultMap will not be performed)

excludeProperty

String[]

no

{}

Attribute names that need to be excluded @since 3.3.1

2.7.2 @TableId
  • @TableId
    • Description: Primary key annotation
    • Where to use: Entity class primary key field
    • IdType.AUTO, consistent with mysql primary key auto-increment

Attributes

type

Must be specified

default value

describe

value

String

no

""

Primary key field name

type

Enum

no

IdType.NONE

Specify primary key type

  • dType

value

describe

AUTO

Database ID auto-increment

NONE

Stateless, this type has no primary key set (the annotation is equivalent to following the global, and the global Rio is approximately equal to INPUT)

INPUT

Set the primary key value yourself before inserting

ASSIGN_ID

Assign ID (primary key type is Number (Long and Integer) or String) (since 3.3.0), use the method nextId of the interface IdentifierGenerator (the default implementation class is DefaultIdentifierGenerator snowflake algorithm)

ASSIGN_UUID

Assign UUID, the primary key type is String (since 3.3.0), use the method nextUUID of the interface IdentifierGenerator (default default method)

ID_WORKER

Distributed globally unique ID long integer type (please use ASSIGN_ID)

UUID

32-bit UUID string (please use ASSIGN_UUID)

ID_WORKER_STR

Distributed globally unique ID string type (please use ASSIGN_ID)

2.7.3 @TableField
  • @TableField
    • Description: Field annotations (non-primary key)
2.7.4 Example of creating entity class Book
  • Create a new corresponding entity class Book under the folder entity created in [2.6] based on the table book_tab in the newly created database market_db in [2.1.2]

[Example: Book]

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;

@Data                   // set,get方法
@NoArgsConstructor      // 无参构造方法
@AllArgsConstructor     // 有参构造方法
@TableName("book_tab")
public class Book {
    @TableId(value = "book_id", type = IdType.AUTO)
    private Long id;
    @TableField("book_title")
    private String title;
    @TableField("book_author")
    private String author;
    @TableField("book_isbn")
    private String isbn;
    @TableField("book_price")
    private BigDecimal price;
    @TableField("book_publication")
    private Date publication;
    @TableField("book_pages")
    private Long pages;
    @TableField("book_version")
    private Integer version;
    @TableField("book_image_url")
    private String imageUrl;
    @TableField("book_introduction")
    private String introduction;
    @TableField("book_store")
    private Integer store;
    @TableField("book_publisher")
    private Long publisher;
    @TableField("book_type")
    private Long type;
    @TableField("book_comment")
    private String comment;
    @TableField("book_create_time")
    private Date createTime;
    @TableField("book_update_time")
    private Date updateTime;
    @TableField("book_update_by")
    private String updateBy;

}
2.7.5 Supplement
  • @Data
    • set,get method
  • @NoArgsConstructor
    • No-argument constructor
  • @AllArgsConstructor
    • Parametric constructor

2.8 The persistence layer defines the CRUD interface

  • Mapper CRUD interface description
    • Universal CRUD encapsulates the BaseMapper interface, which automatically parses the entity table relationship mapping and converts it into Mybatis internal objects for injection into the container when Mybatis-Plus starts.
    • Generic T is any entity object
    • The parameter Serializable is any type of primary key. Mybatis-Plus does not recommend the use of composite primary keys. Each table has its own unique id primary key.
    • Object Wrapper is a conditional constructor

[Example: IBookDao]

package com.wnhz.market.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wnhz.market.entity.Book;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface IBookDao extends BaseMapper<Book> {
}

2.9 service business layer

2.9.1 service interface

[Example: IBookService add method]

package com.wnhz.market.service;

import com.wnhz.market.entity.Book;

public interface IBookService {
    /**
     * 添加
     *
     * @param book
     */
    void addBook(Book book);
}
2.9.2 Service interface implementation
  • In the IBookService file, place the mouse on the public interface IBookService, press the shortcut key alt+enter, select Implement Interface to automatically generate the interface implementation file, pay attention to whether to change the name and file storage location

[Example: BookServiceImpl]

  • Pay attention to adding the annotation @Service
package com.wnhz.market.service.impl;

import com.wnhz.market.dao.IBookDao;
import com.wnhz.market.entity.Book;
import com.wnhz.market.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BookServiceImpl implements IBookService {
    @Autowired
    IBookDao bookDao;
    @Override
    public void addBook(Book book) {
          bookDao.insert(book);
    }
}

2.10 Unit testing-junit

  • Use the shortcut key alt+insert in BookServiceImpl, then select test. Pay attention to selecting JUnit4 to automatically generate unit test files. Pay attention to adding the annotations @SpringBootTest, @RunWith(SpringJUnit4ClassRunner.class), and @Test.

[Example: BookServiceImplTest]

package com.wnhz.market.service.impl;

import com.wnhz.market.entity.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.math.BigDecimal;
import java.util.Date;

import static org.junit.Assert.*;

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class BookServiceImplTest {
    @Autowired
    BookServiceImpl bookService;

    @Test
    public void addBook() {
        Book book = new Book();
        book.setTitle("普罗米修斯");
        book.setAuthor("东野圭吾");
        book.setIsbn("1806348888");
        book.setPrice(new BigDecimal(33.8));
        book.setPublication(new Date());
        book.setImageUrl("封面图片地址");
        book.setComment("受益颇多");
        book.setIntroduction("小说经典之作");
        book.setPages(new Long(188));
        book.setStore(999);
        book.setCreateTime(new Date());
        book.setUpdateTime(new Date());
        book.setUpdateBy("作者");
        book.setType(new Long(1));
        book.setVersion(3);
        book.setPublisher(new Long(1));
        bookService.addBook(book);

    }
}

Guess you like

Origin blog.csdn.net/chaojichunshen/article/details/131566670