上一篇“初識SpringBoot–入門SpringBoot”
一、前言
- Mybatis:資料持久化架構
- Mybatis-Plus:對Mybatis進行了增強,它封裝了基本的增删改查操作,使我們自己不需要再去寫很多重複的代碼,大大解放了生産力!
二、建立項目
建立成功後删除src下面的test目錄
三、目錄結構
四、pom.xml
修改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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.llh</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>1.0.0</version>
<name>spring-boot-demo</name>
<description>springboot project description</description>
<properties>
<mybatis-spring-boot.version>2.1.4</mybatis-spring-boot.version>
<mybatis-plus.version>3.4.2</mybatis-plus.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>${mybatis-spring-boot.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
</dependencies>
</project>
說明:
中 spring-boot-starter-parent 幫我們做了SpringBoot相關依賴包的版本号管理,是以有些依賴包不需要我們自己去寫
但像 mybatis-plus-boot-starter 它是不屬于spring-boot相關的, parent中沒有做版本号管理,是以還需要手動寫一下。
五、sql和application.properties
5.1 導入sql語句
CREATE TABLE `user_info` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '使用者id',
`username` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '使用者名' COLLATE 'utf8mb4_general_ci',
`password` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '密碼' COLLATE 'utf8mb4_general_ci',
`create_time` DATETIME NOT NULL COMMENT '建立時間',
PRIMARY KEY (`id`) USING BTREE
);
說明:建立一個資料庫,然後運作上述sql語句,生成使用者表,主要就下面四個字段
- id 使用者id 自增主鍵
- username 使用者名
- password 密碼
- create_time 建立時間
5.2 修改application.properties配置檔案
# 應用名稱
spring.application.name=spring-boot-demo
server.port=8888
# 資料庫相關
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.username=root
spring.datasource.password=0320
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# mybatis相關
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
說明:
- 資料庫位址 localhost:3306/demo, demo就是資料庫名稱
- 資料庫使用者名 spring.datasource.username
- 資料庫密碼 spring.datasource.password
- mybatis.mapper-locations 配置掃碼xml檔案
六、邏輯代碼
SpringBootDemoApplication 類
package com.llh.springbootdemo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author llh
*/
@SpringBootApplication
@MapperScan(value = "com.llh.springbootdemo.mapper")
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
說明:啟動類上加上
作用是掃描到mapper裡面中的類,注意路徑要和項目中實際路徑一緻
UserInfo 類
package com.llh.springbootdemo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
/**
* @author llh
*/
public class UserInfo {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String username;
private String password;
private LocalDateTime createTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "UserInfo{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", createTime=" + createTime +
'}';
}
}
說明:這裡類成員變量和資料庫字段對應,Mybatis自動做了駝峰法到下劃線的轉換
如:資料庫 create_time -> 類變量 createTime
UserInfoMapper 類
package com.llh.springbootdemo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.llh.springbootdemo.entity.UserInfo;
/**
* @author llh
*/
public interface UserInfoMapper extends BaseMapper<UserInfo> {
}
說明:BaseMapper 類封裝了dao層基本的增删改查操作
mapper/UserInfoMapper.xml
<?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.llh.springbootdemo.mapper.UserInfoMapper">
</mapper>
說明:這裡的namespace和上述的UserInfoMapper路徑對應一緻
UserInfoService 類
package com.llh.springbootdemo.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.llh.springbootdemo.entity.UserInfo;
/**
* @author llh
*/
public interface UserInfoService extends IService<UserInfo> {
}
說明:這裡IService封裝了service層基本的增删改查
UserInfoServiceImpl 類
package com.llh.springbootdemo.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.llh.springbootdemo.entity.UserInfo;
import com.llh.springbootdemo.mapper.UserInfoMapper;
import com.llh.springbootdemo.service.UserInfoService;
import org.springframework.stereotype.Service;
/**
* @author llh
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
}
UserInfoController 類
package com.llh.springbootdemo.controller;
import com.llh.springbootdemo.entity.UserInfo;
import com.llh.springbootdemo.service.UserInfoService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
/**
* @author llh
*/
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {
@Resource
private UserInfoService userInfoService;
@PostMapping("/add")
public Boolean add(@RequestBody UserInfo userInfo) {
userInfo.setCreateTime(LocalDateTime.now());
return userInfoService.save(userInfo);
}
@GetMapping("/delete/{id}")
public Boolean delete(@PathVariable Long id) {
return userInfoService.removeById(id);
}
@PostMapping("/update")
public Boolean update(@RequestBody UserInfo userInfo) {
return userInfoService.updateById(userInfo);
}
@GetMapping("/get/{id}")
public UserInfo get(@PathVariable Long id) {
return userInfoService.getById(id);
}
@GetMapping("/list")
public List<UserInfo> list() {
return userInfoService.list();
}
}
說明:
- 增删改查接口,基本上不需要自己寫sql,直接調用Mybatis-Plus封裝好的接口。
七、結語
用Mybatis-Plus是不是很簡單,嘿嘿。
簡單看一下,Mybatis-Plus增删改查方法接口如下:
Mybatis屬于半配置型的資料持久化架構,JPA是直接封裝了所有的SQL操作,相對于JPA來說Mybatis更靈活,可以自定義SQL。同時Mybatis-Plus又為你封裝了常用的增删改查操作,這樣既可以在特殊情況下自定義SQL,又避免了寫大量重複的增删改查。
當然Mybatis-Plus還有很多更好玩的東西,比如自動填入字段值,像是建立時間、更新時間字段都可以通過統一攔截直接指派,不需要手動去set。還比如有多租戶、邏輯删除等。這些後續再說。
同步微信公衆号:小虎哥的技術部落格