首頁 > 軟體

springboot整合mybatisplus的方法詳解

2022-03-28 16:00:41

POM:

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>3.5.1</version>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>2.1.4</version>
</dependency>

如下圖所示,mybatis-plus-boot-starter 已經引入了jdbc 所以無需在引入 jdbc的依賴

application.yaml:

只需要 填寫資料來源設定即可 。

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/kaoyan?serverTimezone=UTC
    password: admin
    username: root
    driver-class-name: com.mysql.cj.jdbc.Driver

POJO:

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@TableName(value = "user") // 指定查詢的表名為 user 
public class UserPlus {
    // 以下為 mybatis-plus測試
    private Integer id;
    private String name;
    private Integer age;
    private String email;
}

mapper介面:

特別簡潔

package com.hoan.demo03242.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hoan.demo03242.bean.UserPlus;
public interface UserPlusMapper extends BaseMapper<UserPlus> {
}

包掃描:

測試:

@SpringBootTest
class Demo03242ApplicationTests {
    @Autowired
    UserPlusMapper userPlusMapper;
    @Test
    void contextLoads() {
        UserPlus user = userPlusMapper.selectById(1);
        System.out.println(user.toString());
    }
}

總結

本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注it145.com的更多內容! 


IT145.com E-mail:sddin#qq.com