基于SpringBoot的SSMP的整合案例
簡(jiǎn)單介紹
模塊創(chuàng)建
添加spring WEB 和MYSQL driver的依賴
然后手動(dòng)添加Mybatis-plus和druid的依賴
改寫(xiě)配置文件端口
創(chuàng)建實(shí)體類
在domain包下面創(chuàng)建Book類,使用lombook技術(shù)自動(dòng)配置相關(guān)get set操作
Lombok,一個(gè)Java類庫(kù),提供了一組注解,簡(jiǎn)化POJO實(shí)體類開(kāi)發(fā)
添加lombok依賴,不需要添加坐標(biāo),因?yàn)閜arent已經(jīng)包含坐標(biāo)
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
使用@Data注解簡(jiǎn)化開(kāi)發(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測(cè)試查詢方法
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分頁(yè)查詢
- 創(chuàng)建分頁(yè)對(duì)象Page
- 創(chuàng)建分頁(yè)攔截器
// 分頁(yè)查詢操作 需要在配置類中添加攔截器 @Test void testGetPage(){ IPage page = new Page(1,2);//page是IPage的實(shí)現(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());// 添加分頁(yè)攔截器 return interceptor; } }
按照條件進(jìn)行查詢
使用QueryWrapper對(duì)象封裝查詢條件,推薦使用LambdaQueryWrapper對(duì)象,所有查詢操作封裝成方法調(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開(kāi)發(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(); // 分頁(yè)查詢接口 IPage<Book> getPage(int currentPage, int pageSize); }
- 定義service接口的實(shí)現(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; // 將該實(shí)現(xiàn)類定義成業(yè)務(wù)層的一個(gè)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)建分頁(yè)查詢對(duì)象 IPage page = new Page(currentPage,pageSize); return bookDao.selectPage(page,null); } }
- 注入bookService接口資源 進(jìn)行查詢測(cè)試
// 分頁(yè)查詢 @Test void testGetPage1(){ IPage<Book> page = bookService.getPage(1,5); System.out.println(page.getRecords()); } // 使用業(yè)務(wù)層進(jìn)行查詢 @Test void test1(){ System.out.println(bookService.getById(4)); }
業(yè)務(wù)層Service快速開(kāi)發(fā)
- 首先定義一個(gè)IBookService
package com.ustc.service; import com.baomidou.mybatisplus.extension.service.IService; import com.ustc.domain.Book; public interface IBookService extends IService<Book> { }
- 實(shí)現(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) 快速開(kāi)發(fā)Service
- 使用通用實(shí)現(xiàn)類(ServiceImpl<M,T>) 快速開(kāi)發(fā)ServiceImpl
- 可以在通用接口的基礎(chǔ)上做功能重載或者功能追加
- 注意重載時(shí)不要覆蓋原始的操作,避免原始提供的功能丟失
表現(xiàn)層開(kāi)發(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ù) 通過(guò)請(qǐng)求體傳輸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進(jìn)行查詢 使用pathVariable注解 使得url參數(shù) 賦值到形參 @GetMapping("{id}") public Book getById(@PathVariable Integer id){ return bookService.getById(id); } }
使用postman做測(cè)試
表現(xiàn)層 實(shí)現(xiàn)分頁(yè)查詢
- 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è)計(jì)表現(xiàn)層返回結(jié)果的模型類,用于后端與前端進(jìn)行數(shù)據(jù)格式統(tǒng)一,也成為前后端數(shù)據(jù)協(xié)議
首先定義一個(gè)R類,這里的flag表示后端的操作有沒(méi)有成功,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; } }
之后改寫(xiě)Controller的接口方法,插入,修改,刪除操作只需要傳入Boolean參數(shù)即可,對(duì)于需要返回?cái)?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ù) 通過(guò)請(qǐng)求體傳輸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進(jìn)行查詢 使用pathVariable注解 使得url參數(shù) 賦值到形參 @GetMapping("{id}") public R getById(@PathVariable Integer id){ // 第一個(gè)參數(shù)是flag 第二個(gè)參數(shù)是 object對(duì)象 data R r = new R(true,bookService.getById(id)); return r; } // 分頁(yè)查詢操作 @GetMapping("/page/{currentPage}/{pageSize}") public R getPage(@PathVariable int currentPage,@PathVariable int pageSize){ return new R(true,bookService.getPage(currentPage,pageSize)); } }
意義:
- 設(shè)計(jì)統(tǒng)一的返回值結(jié)果類型便于前端開(kāi)發(fā)讀取數(shù)據(jù)
- 返回值結(jié)果類型可以根據(jù)需求自行設(shè)定,沒(méi)有固定的格式
- 返回值結(jié)果類型用于后端和前端進(jìn)行數(shù)據(jù)格式統(tǒng)一,也稱之為前后端數(shù)據(jù)協(xié)議
查詢所有書(shū)本信息
發(fā)送異步請(qǐng)求,將請(qǐng)求后端查詢的數(shù)據(jù)傳給前端,前端數(shù)據(jù)雙向綁定進(jìn)行數(shù)據(jù)展示
添加書(shū)本
使用axios請(qǐng)求將前端的請(qǐng)求包括數(shù)據(jù)發(fā)送給后端
- 請(qǐng)求方式使用POST調(diào)用后臺(tái)對(duì)應(yīng)操作
- 添加操作結(jié)束之后動(dòng)態(tài)刷新頁(yè)面加載數(shù)據(jù)
- 根據(jù)操作結(jié)果不同,顯示對(duì)應(yīng)的提示信息
- 彈出添加div時(shí)清除表單數(shù)據(jù)
handleAdd () { // 使用axios 將數(shù)據(jù)發(fā)送給后端 post請(qǐng)求 發(fā)送請(qǐng)求 返回res 檢查flag操作是否成功 axios.post("/books",this.formData).then((res)=>{ // 判斷當(dāng)前操作是否成功 if(res.data.flag){ // 關(guān)閉彈層 // 點(diǎn)擊確定 發(fā)送數(shù)據(jù)之后 關(guān)閉彈窗 this.dialogFormVisible = false; this.$message.success("添加成功"); }else{ this.$message.error("添加失敗"); } }).finally(()=>{ // 重新加載數(shù)據(jù) this.getAll(); }); },
刪除操作
- 請(qǐng)求方式使用Delete調(diào)用后臺(tái)對(duì)應(yīng)操作
- 刪除操作需要傳遞當(dāng)前行數(shù)據(jù)對(duì)應(yīng)的id值到后臺(tái)
- 刪除操作結(jié)束之后動(dòng)態(tài)刷新頁(yè)面加載數(shù)據(jù)
- 根據(jù)操作結(jié)果的不同,顯示對(duì)應(yīng)的提示信息
- 刪除操作前彈出提示框避免誤操作
// 刪除 handleDelete(row) { // axios發(fā)送異步請(qǐng)求 使用deleteMapping 參數(shù)是id 刪除操作 this.$confirm("此操作永久刪除當(dāng)前信息,是否繼續(xù)?","提示",{type:"info"}).then(()=>{ axios.delete("/books/"+row.id).then((res)=>{ if(res.data.flag){ this.$message.success("刪除成功"); }else{ this.$message.error("刪除失敗"); } }).finally(()=>{ // 不管刪除成功 還是失敗 都會(huì)刷新頁(yè)面 this.getAll(); }); }).catch(()=>{ this.$message.info("取消操作"); }); },
修改功能
- 加載要修改數(shù)據(jù)通過(guò)傳遞當(dāng)前行數(shù)據(jù)對(duì)應(yīng)的id值到后臺(tái)查詢數(shù)據(jù)
- 利用前端數(shù)據(jù)雙向綁定將查詢到的數(shù)據(jù)進(jìn)行回顯
- 首先點(diǎn)擊編輯按鈕 根據(jù)id加載后端的數(shù)據(jù)
- 然后編輯數(shù)據(jù),傳給后端
//彈出編輯窗口 點(diǎn)擊編輯按鈕 根據(jù)id加載后臺(tái)的數(shù)據(jù) handleUpdate(row) { // 發(fā)送異步請(qǐng)求 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ù)同步失敗 ,自動(dòng)刷新"); } }).finally(()=>{ // 重新加載數(shù)據(jù) 也就是刷新頁(yè)面 this.getAll(); }); }, //編輯按鈕:這個(gè)按鈕的作用就是根據(jù)id查詢數(shù)據(jù)信息 然后填充到頁(yè)面即可 put操作將表單修改的數(shù)據(jù)進(jìn)行回顯 handleEdit() { axios.put("/books",this.formData).then((res)=>{ // 判斷當(dāng)前操作是否成功 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){ //記錄日志 //通知運(yùn)維 //通知開(kāi)發(fā) ex.printStackTrace(); return new R("服務(wù)器故障,請(qǐng)稍后再試!"); } }
- 使用注解@RestControllerAdvice定義SpringMVC異常處理器來(lái)處理異常
- 異常處理器必須被掃描加載,否則無(wú)法生效
- 表現(xiàn)層返回結(jié)果的模型類中添加消息屬性用來(lái)傳遞消息到頁(yè)面
添加分頁(yè)查詢
發(fā)起請(qǐng)求調(diào)用,將當(dāng)前頁(yè)碼之和每頁(yè)的展示數(shù)據(jù)量 傳到后端進(jìn)行查詢
getAll() { //發(fā)送異步請(qǐng)求 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; // 將請(qǐng)求后端發(fā)送的數(shù)據(jù)傳給前端 展示 this.dataList = res.data.data.records; }); },
- 使用el分頁(yè)組件
- 定義分頁(yè)組件綁定的數(shù)據(jù)模型
- 異步調(diào)用獲取分頁(yè)數(shù)據(jù)
- 分頁(yè)數(shù)據(jù)頁(yè)面回顯
以上就是基于SpringBoot的SSMP的整合案例的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot整合SSMP的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
微服務(wù)中使用Maven BOM來(lái)管理你的版本依賴詳解
這篇文章主要介紹了微服務(wù)中使用Maven BOM來(lái)管理你的版本依賴,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12SpringBoot整合jasypt進(jìn)行重要數(shù)據(jù)加密的操作代碼
Jasypt(Java?Simplified?Encryption)是一個(gè)專注于簡(jiǎn)化Java加密操作的開(kāi)源工具,它提供了一種簡(jiǎn)單而強(qiáng)大的方式來(lái)處理數(shù)據(jù)的加密和解密,使開(kāi)發(fā)者能夠輕松地保護(hù)應(yīng)用程序中的敏感信息,本文給大家介紹了SpringBoot整合jasypt進(jìn)行重要數(shù)據(jù)加密,需要的朋友可以參考下2024-05-05mybatis中實(shí)現(xiàn)讓返回值與bean中字段相匹配
這篇文章主要介紹了mybatis中實(shí)現(xiàn)讓返回值與bean中字段相匹配,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10Java 根據(jù)貸款年限對(duì)應(yīng)利率計(jì)算功能實(shí)現(xiàn)解析
這篇文章主要介紹了Java 根據(jù)貸款年限對(duì)應(yīng)利率計(jì)算功能實(shí)現(xiàn)解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10深入淺析springboot中static和templates區(qū)別
這篇文章主要介紹了springboot中static和templates區(qū)別,本文通過(guò)圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02基于SpringBoot實(shí)現(xiàn)圖片防盜鏈的兩種方式
出于安全和性能的考慮,我們希望服務(wù)器返回的圖片資源僅在指定網(wǎng)站內(nèi)展示,防止爬蟲(chóng)或其它站點(diǎn)直接引用圖片地址進(jìn)行下載或展示,進(jìn)而消耗服務(wù)器資源,所以本文給大家介紹了基于SpringBoot實(shí)現(xiàn)圖片防盜鏈的兩種方式,需要的朋友可以參考下2025-02-02SpringMVC用JsonSerialize日期轉(zhuǎn)換方法
下面小編就為大家?guī)?lái)一篇SpringMVC用JsonSerialize日期轉(zhuǎn)換方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起 小編過(guò)來(lái)看看吧2016-11-11Java Springboot 后端使用Mockito庫(kù)進(jìn)行單元測(cè)試流程分析
使用Mock進(jìn)行單元測(cè)試可以避免啟動(dòng)整個(gè)Spring框架,節(jié)省時(shí)間并降低外部依賴影響,Mock允許模擬外部方法和類,專注于測(cè)試方法的功能邏輯,本文給大家介紹Java Springboot 后端使用Mockito庫(kù)進(jìn)行單元測(cè)試流程分析,感興趣的朋友跟隨小編一起看看吧2024-10-10