MBP01 Import Mybatis-plus into Spring Boot
Tags: mybatisplus, springboot
Published: 2021-01-24 08:24:28

# 在Spring Boot项目内引入mybatis-plus

## Install

Directly add maven dependencies in [pom.xml]. Note that the version of `mysql-connector` is no need to mention (see comment).

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

  <!-- mysql connector -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <!-- The managed version is 8.0.21 The artifact is managed in org.springframework.boot:spring-boot-dependencies:2.3.4.RELEASE -->
  </dependency>
```

注意我们是在spring boot中使用mybatis-plus，所以引入的包必须是`mybatis-plus-boot-starter`。

## Configure

Write configurations in the [application.properties] under the resources folder:

```
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/xxx?useSSL=true
spring.datasource.username=xxx
spring.datasource.password=xxxxxx
```

## Entity class

Before creating entity classes, database tables should be designed and created.

In this example, I just create a simple user table and a objective table. And there is a one-to-many relationship.

```sql
create table users (
  id integer primary key not null auto_increment,
  username varchar(50) not null,
  password varchar(100) not null,
  question varchar(150),
  answer varchar(50)
);

create table objective (
  id integer primary key not null auto_increment,
  name varchar(50) not null,
  user_id integer not null,
  foreign key (user_id) REFERENCES users (id)
);
```

As for the entity class, I named it `AppUser`. We need to manually map the class to the table as they are different.

I recommend to use annotation which is clear and readable:

```java
@TableName(value = "users")
public class AppUser {
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    @TableField(value = "username")
    private String username;
    @TableField(value = "password")
    private String password;
    @TableField(value = "question")
    private String question;
    @TableField(value = "answer")
    private String answer;
    @TableField(exit = false)
    private List<Objective> objectives;
}
```

If the column name in table is exactly the same with param name in class, then `@TableField` could be omitted.

`@TableField(exit = false)` indicates that there is no column in database that maps the property.

### Primary key

We can use `type` property in `@TableId` to set the strategy in table's primary key.

Here are some options that will discussed in this article:

- ASSIGN_ID
- AUTO
- ASSIGN_UUID
- INPUT

**ASSIGN_ID**

The default strategy. Using algorithm (SnowFlake) to create a unique id. The type of primary key should be Long or String in Java, and BIGINT or VARCHAR in mysql. 

**AUTO**

Using the auto increment strategy which is supported in database.

**ASSIGN_UUID**

Similar to `ASSIGN_ID`, but remove all '-' and the type must be String and VARCHAR.

**INPUT**

The id is input by users.

## Mapper class

Just create an interface that extends BaseMapper<T>. The interface has already intergrates basic CRUD methods.

```java
public interface AppUserMapper extends BaseMapper<AppUser> {
    //public AppUser find
}
```

There are two ways to let Spring load the mapper classes:

1. Add `@Mapper` to every mapper classes, or
2. Add `@MapperScan(basePackages="com...mapper")` at the application entry class (shown below in the code)

```java
@SpringBootApplication
@MapperScan(basePackages="com.myrrh.passbook.mapper")
public class PassbookApplication {

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

## Test

Just add some code in a Controller class (to make it simple, I skipped the service layer).

To run the code, just start the project and type the url in the browser.

```java
@Autowired
AppUserMapper appUserMapper;

@RequestMapping("/testdb")
@ResponseBody
public String testdb() {
    // the id type is AUTO
    AppUser au = new AppUser("jisd", "89hf3", "My post-graduate best friend", "Hue");
    appUserMapper.insert(au);
    return "done";
}
```