基于SpringBoot的SSMP的整合案例
簡單介紹

模塊創(chuàng)建
添加spring WEB 和MYSQL driver的依賴
然后手動添加Mybatis-plus和druid的依賴

改寫配置文件端口

創(chuàng)建實體類
在domain包下面創(chuàng)建Book類,使用lombook技術(shù)自動配置相關(guān)get set操作
Lombok,一個Java類庫,提供了一組注解,簡化POJO實體類開發(fā)
添加lombok依賴,不需要添加坐標,因為parent已經(jīng)包含坐標
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>使用@Data注解簡化開發(fā)
package com.ustc.domain;
import lombok.Data;
@Data
public class Book {
private Integer id;
private String type;
private String name;
private String description;
}導(dǎo)入Mybatis-plus和druid的配置文件

server:
port: 80
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/da?serverTimezone=UTC
username: root
password: 123456
mybatis-plus:
global-config:
db-config:
table-prefix: tbl_
# 配置druid使用junit測試查詢方法
package com.ustc;
import com.ustc.Dao.BookDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.ustc.domain.Book;
@SpringBootTest
class Sp11ApplicationTests {
@Autowired
private BookDao bookDao;
@Test
void contextLoads() {
System.out.println(bookDao.selectById(1));
}
// 插入操作
@Test
void testSave(){
Book book = new Book();
book.setId(10);
book.setType("心理");
book.setName("111111111111111111");
book.setDescription("dshf");
bookDao.insert(book);
}
// 更新操作
@Test
void testSave1(){
Book book = new Book();
book.setId(10);
book.setType("心理");
book.setName("如何成為富婆");
book.setDescription("dshf");
bookDao.updateById(book);
}
// 刪除操作
@Test
void testdelete(){
bookDao.deleteById(1);
}
// 查詢?nèi)坎僮?
@Test
void testGetAll(){
System.out.println(bookDao.selectList(null));
}
}MP分頁查詢
- 創(chuàng)建分頁對象Page
- 創(chuàng)建分頁攔截器
// 分頁查詢操作 需要在配置類中添加攔截器
@Test
void testGetPage(){
IPage page = new Page(1,2);//page是IPage的實現(xiàn)類
// 輸出數(shù)據(jù)
System.out.println(bookDao.selectPage(page,null).getRecords());
}package com.ustc.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MPConfig {
// 定義攔截器
// 注入攔截器資源
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
// 創(chuàng)建mP攔截器
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());// 添加分頁攔截器
return interceptor;
}
}按照條件進行查詢
使用QueryWrapper對象封裝查詢條件,推薦使用LambdaQueryWrapper對象,所有查詢操作封裝成方法調(diào)用
@Test
void testGetBy(){
QueryWrapper<Book> qw = new QueryWrapper<>();
// 設(shè)置查詢條件
qw.like("name","Spring");
bookDao.selectList(qw);// 傳入查詢條件
}
@Test
void testGetBy1(){
LambdaQueryWrapper<Book> qw = new LambdaQueryWrapper<>();
// 設(shè)置查詢條件
qw.like(Book::getName,"Spring");
bookDao.selectList(qw);// 傳入查詢條件
}業(yè)務(wù)層Service開發(fā)
Service層接口定義與數(shù)據(jù)層接口定義具有較大的區(qū)別,不要混用
- selectByUserNameAndPassword(String username,String password) 數(shù)據(jù)層
- login(String username,String password) 業(yè)務(wù)層
- 定義 service接口
package com.ustc.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ustc.domain.Book;
import org.springframework.stereotype.Service;
import java.util.List;
public interface BookService {
// 業(yè)務(wù)層先定義 業(yè)務(wù)的接口
Boolean save(Book book);
Boolean update(Book book);
Boolean delete(Integer id);
Book getById(Integer id);
List<Book> getAll();
// 分頁查詢接口
IPage<Book> getPage(int currentPage, int pageSize);
}- 定義service接口的實現(xiàn)類
package com.ustc.service.Impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ustc.Dao.BookDao;
import com.ustc.domain.Book;
import com.ustc.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
// 將該實現(xiàn)類定義成業(yè)務(wù)層的一個bean資源
@Service
public class BookServiceImpl implements BookService {
// 注入數(shù)據(jù)層的接口
@Autowired
private BookDao bookDao;
@Override
public Boolean save(Book book) {
return bookDao.insert(book) > 0;
}
@Override
public Boolean update(Book book) {
return bookDao.updateById(book) > 0;
}
@Override
public Boolean delete(Integer id) {
return bookDao.deleteById(id) > 0;
}
@Override
public Book getById(Integer id) {
return bookDao.selectById(id);
}
@Override
public List<Book> getAll() {
return bookDao.selectList(null);
}
@Override
public IPage<Book> getPage(int currentPage, int pageSize) {
// 首先創(chuàng)建分頁查詢對象
IPage page = new Page(currentPage,pageSize);
return bookDao.selectPage(page,null);
}
}- 注入bookService接口資源 進行查詢測試
// 分頁查詢
@Test
void testGetPage1(){
IPage<Book> page = bookService.getPage(1,5);
System.out.println(page.getRecords());
}
// 使用業(yè)務(wù)層進行查詢
@Test
void test1(){
System.out.println(bookService.getById(4));
}業(yè)務(wù)層Service快速開發(fā)
- 首先定義一個IBookService
package com.ustc.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ustc.domain.Book;
public interface IBookService extends IService<Book> {
}- 實現(xiàn)IBookService接口
package com.ustc.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ustc.domain.Book;
public interface IBookService extends IService<Book> {
}- 使用通用接口(IService) 快速開發(fā)Service
- 使用通用實現(xiàn)類(ServiceImpl<M,T>) 快速開發(fā)ServiceImpl
- 可以在通用接口的基礎(chǔ)上做功能重載或者功能追加
- 注意重載時不要覆蓋原始的操作,避免原始提供的功能丟失
表現(xiàn)層開發(fā)
package com.ustc.Controller;
import com.ustc.domain.Book;
import com.ustc.service.IBookService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private IBookService bookService;
// 查詢?nèi)啃畔?
@GetMapping("/search")
public List<Book> getAll(){
return bookService.list();
}
// 插入數(shù)據(jù) 這里的參數(shù) 通過請求體傳輸json數(shù)據(jù) 添加RequestBody注解
@PostMapping("/insert")
public Boolean save(@RequestBody Book book){
return bookService.save(book);
}
// 修改數(shù)據(jù)
@PutMapping("/update")
public Boolean update(@RequestBody Book book){
return bookService.modify(book);
}
// 刪除數(shù)據(jù)
@DeleteMapping("/delete/{id}")
public Boolean delete(@PathVariable Integer id){
return bookService.delete(id);
}
// 根據(jù)id進行查詢 使用pathVariable注解 使得url參數(shù) 賦值到形參
@GetMapping("{id}")
public Book getById(@PathVariable Integer id){
return bookService.getById(id);
}
}使用postman做測試

表現(xiàn)層 實現(xiàn)分頁查詢
- Controller
@GetMapping("/page/{currentPage}/{pageSize}")
public IPage<Book> getPage(@PathVariable int currentPage,@PathVariable int pageSize){
return bookService.getPage(currentPage,pageSize);
}- Service
@Override
public IPage<Book> getPage(int currentPage, int pageSize) {
IPage page = new Page(currentPage,pageSize);
bookDao.selectPage(page,null);
return page;
}表現(xiàn)層消息一致性的處理


設(shè)計表現(xiàn)層返回結(jié)果的模型類,用于后端與前端進行數(shù)據(jù)格式統(tǒng)一,也成為前后端數(shù)據(jù)協(xié)議
首先定義一個R類,這里的flag表示后端的操作有沒有成功,data表示后端傳輸?shù)臄?shù)據(jù)
package com.ustc.Controller.utils;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.ustc.domain.Book;
import lombok.Data;
@Data
public class R {
private Boolean flag;
private Object data;
public R(){}
public R(Boolean flag){
this.flag = flag;
}
// 構(gòu)造函數(shù)重載
public R(Boolean flag,Object data){
this.flag = flag;
this.data = data;
}
}之后改寫Controller的接口方法,插入,修改,刪除操作只需要傳入Boolean參數(shù)即可,對于需要返回數(shù)據(jù)的接口,使用另一種構(gòu)造方法
package com.ustc.Controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ustc.Controller.utils.R;
import com.ustc.domain.Book;
import com.ustc.service.IBookService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private IBookService bookService;
// 查詢?nèi)啃畔?
@GetMapping("/search")
public R getAll(){
return new R(true,bookService.list());
}
// 插入數(shù)據(jù) 這里的參數(shù) 通過請求體傳輸json數(shù)據(jù) 添加RequestBody注解
@PostMapping("/insert")
public R save(@RequestBody Book book){
return new R(bookService.save(book));
}
// 修改數(shù)據(jù)
@PutMapping("/update")
public R update(@RequestBody Book book){
// return bookService.modify(book);
return new R(bookService.modify(book));
}
// 刪除數(shù)據(jù)
@DeleteMapping("/delete/{id}")
public R delete(@PathVariable Integer id){
return new R(bookService.delete(id));
}
// 根據(jù)id進行查詢 使用pathVariable注解 使得url參數(shù) 賦值到形參
@GetMapping("{id}")
public R getById(@PathVariable Integer id){
// 第一個參數(shù)是flag 第二個參數(shù)是 object對象 data
R r = new R(true,bookService.getById(id));
return r;
}
// 分頁查詢操作
@GetMapping("/page/{currentPage}/{pageSize}")
public R getPage(@PathVariable int currentPage,@PathVariable int pageSize){
return new R(true,bookService.getPage(currentPage,pageSize));
}
}意義:
- 設(shè)計統(tǒng)一的返回值結(jié)果類型便于前端開發(fā)讀取數(shù)據(jù)
- 返回值結(jié)果類型可以根據(jù)需求自行設(shè)定,沒有固定的格式
- 返回值結(jié)果類型用于后端和前端進行數(shù)據(jù)格式統(tǒng)一,也稱之為前后端數(shù)據(jù)協(xié)議

查詢所有書本信息
發(fā)送異步請求,將請求后端查詢的數(shù)據(jù)傳給前端,前端數(shù)據(jù)雙向綁定進行數(shù)據(jù)展示


添加書本
使用axios請求將前端的請求包括數(shù)據(jù)發(fā)送給后端


- 請求方式使用POST調(diào)用后臺對應(yīng)操作
- 添加操作結(jié)束之后動態(tài)刷新頁面加載數(shù)據(jù)
- 根據(jù)操作結(jié)果不同,顯示對應(yīng)的提示信息
- 彈出添加div時清除表單數(shù)據(jù)
handleAdd () {
// 使用axios 將數(shù)據(jù)發(fā)送給后端 post請求 發(fā)送請求 返回res 檢查flag操作是否成功
axios.post("/books",this.formData).then((res)=>{
// 判斷當前操作是否成功
if(res.data.flag){
// 關(guān)閉彈層
// 點擊確定 發(fā)送數(shù)據(jù)之后 關(guān)閉彈窗
this.dialogFormVisible = false;
this.$message.success("添加成功");
}else{
this.$message.error("添加失敗");
}
}).finally(()=>{
// 重新加載數(shù)據(jù)
this.getAll();
});
},刪除操作
- 請求方式使用Delete調(diào)用后臺對應(yīng)操作
- 刪除操作需要傳遞當前行數(shù)據(jù)對應(yīng)的id值到后臺
- 刪除操作結(jié)束之后動態(tài)刷新頁面加載數(shù)據(jù)
- 根據(jù)操作結(jié)果的不同,顯示對應(yīng)的提示信息
- 刪除操作前彈出提示框避免誤操作
// 刪除
handleDelete(row) {
// axios發(fā)送異步請求 使用deleteMapping 參數(shù)是id 刪除操作
this.$confirm("此操作永久刪除當前信息,是否繼續(xù)?","提示",{type:"info"}).then(()=>{
axios.delete("/books/"+row.id).then((res)=>{
if(res.data.flag){
this.$message.success("刪除成功");
}else{
this.$message.error("刪除失敗");
}
}).finally(()=>{
// 不管刪除成功 還是失敗 都會刷新頁面
this.getAll();
});
}).catch(()=>{
this.$message.info("取消操作");
});
},修改功能
- 加載要修改數(shù)據(jù)通過傳遞當前行數(shù)據(jù)對應(yīng)的id值到后臺查詢數(shù)據(jù)
- 利用前端數(shù)據(jù)雙向綁定將查詢到的數(shù)據(jù)進行回顯
- 首先點擊編輯按鈕 根據(jù)id加載后端的數(shù)據(jù)
- 然后編輯數(shù)據(jù),傳給后端
//彈出編輯窗口 點擊編輯按鈕 根據(jù)id加載后臺的數(shù)據(jù)
handleUpdate(row) {
// 發(fā)送異步請求
axios.get("/books/"+row.id).then((res)=>{
if(res.data.flag && res.data.data != null){
// 內(nèi)容賦值 彈出編輯窗口 然后將數(shù)據(jù)填充上去
this.dialogFormVisible4Edit = true;
this.formData = res.data.data;
}else{
this.$message.error("數(shù)據(jù)同步失敗 ,自動刷新");
}
}).finally(()=>{
// 重新加載數(shù)據(jù) 也就是刷新頁面
this.getAll();
});
},
//編輯按鈕:這個按鈕的作用就是根據(jù)id查詢數(shù)據(jù)信息 然后填充到頁面即可 put操作將表單修改的數(shù)據(jù)進行回顯
handleEdit() {
axios.put("/books",this.formData).then((res)=>{
// 判斷當前操作是否成功
if(res.data.flag){
// 關(guān)閉彈窗
this.dialogFormVisible4Edit = false;
this.$message.success("添加成功");
}else{
this.$message.error("添加失敗");
}
});
},異常處理功能
自定義異常
package com.itheima.controller.utils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//作為springmvc的異常處理器
//@ControllerAdvice
@RestControllerAdvice
public class ProjectExceptionAdvice {
//攔截所有的異常信息
@ExceptionHandler(Exception.class)
public R doException(Exception ex){
//記錄日志
//通知運維
//通知開發(fā)
ex.printStackTrace();
return new R("服務(wù)器故障,請稍后再試!");
}
}- 使用注解@RestControllerAdvice定義SpringMVC異常處理器來處理異常
- 異常處理器必須被掃描加載,否則無法生效
- 表現(xiàn)層返回結(jié)果的模型類中添加消息屬性用來傳遞消息到頁面
添加分頁查詢
發(fā)起請求調(diào)用,將當前頁碼之和每頁的展示數(shù)據(jù)量 傳到后端進行查詢
getAll() {
//發(fā)送異步請求
axios.get("/books/" + this.pagination.currentPage + "/" + this.pagination.pageSize).then((res)=>{
// console.log(res.data);
this.pagination.pageSize = res.data.data.size;
this.pagination.currentPage = res.data.data.current;
this.pagination.total = res.data.data.total;
// 將請求后端發(fā)送的數(shù)據(jù)傳給前端 展示
this.dataList = res.data.data.records;
});
},- 使用el分頁組件
- 定義分頁組件綁定的數(shù)據(jù)模型
- 異步調(diào)用獲取分頁數(shù)據(jù)
- 分頁數(shù)據(jù)頁面回顯
以上就是基于SpringBoot的SSMP的整合案例的詳細內(nèi)容,更多關(guān)于SpringBoot整合SSMP的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
微服務(wù)中使用Maven BOM來管理你的版本依賴詳解
這篇文章主要介紹了微服務(wù)中使用Maven BOM來管理你的版本依賴,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
SpringBoot整合jasypt進行重要數(shù)據(jù)加密的操作代碼
Jasypt(Java?Simplified?Encryption)是一個專注于簡化Java加密操作的開源工具,它提供了一種簡單而強大的方式來處理數(shù)據(jù)的加密和解密,使開發(fā)者能夠輕松地保護應(yīng)用程序中的敏感信息,本文給大家介紹了SpringBoot整合jasypt進行重要數(shù)據(jù)加密,需要的朋友可以參考下2024-05-05
mybatis中實現(xiàn)讓返回值與bean中字段相匹配
這篇文章主要介紹了mybatis中實現(xiàn)讓返回值與bean中字段相匹配,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
Java 根據(jù)貸款年限對應(yīng)利率計算功能實現(xiàn)解析
這篇文章主要介紹了Java 根據(jù)貸款年限對應(yīng)利率計算功能實現(xiàn)解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-10-10
深入淺析springboot中static和templates區(qū)別
這篇文章主要介紹了springboot中static和templates區(qū)別,本文通過圖文實例代碼相結(jié)合給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02
基于SpringBoot實現(xiàn)圖片防盜鏈的兩種方式
出于安全和性能的考慮,我們希望服務(wù)器返回的圖片資源僅在指定網(wǎng)站內(nèi)展示,防止爬蟲或其它站點直接引用圖片地址進行下載或展示,進而消耗服務(wù)器資源,所以本文給大家介紹了基于SpringBoot實現(xiàn)圖片防盜鏈的兩種方式,需要的朋友可以參考下2025-02-02
SpringMVC用JsonSerialize日期轉(zhuǎn)換方法
下面小編就為大家?guī)硪黄猄pringMVC用JsonSerialize日期轉(zhuǎn)換方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起 小編過來看看吧2016-11-11
Java Springboot 后端使用Mockito庫進行單元測試流程分析
使用Mock進行單元測試可以避免啟動整個Spring框架,節(jié)省時間并降低外部依賴影響,Mock允許模擬外部方法和類,專注于測試方法的功能邏輯,本文給大家介紹Java Springboot 后端使用Mockito庫進行單元測試流程分析,感興趣的朋友跟隨小編一起看看吧2024-10-10

