【mybatis】mybatis-plus_CRUD具體操作

1、環境準備

1. 環境準備

1. 引入依賴

在Spring Boot項目的pom.xml文件中引入MyBatis-Plus及其數據庫驅動的依賴。這里以MySQL為例:

<!-- Spring Boot Starter Web -->  
<dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-web</artifactId>  
</dependency>  <!-- MyBatis-Plus Starter -->  
<dependency>  <groupId>com.baomidou</groupId>  <artifactId>mybatis-plus-boot-starter</artifactId>  <version>你的版本號</version>  
</dependency>  <!-- MySQL 驅動 -->  
<dependency>  <groupId>mysql</groupId>  <artifactId>mysql-connector-java</artifactId>  <scope>runtime</scope>  
</dependency>  <!-- Lombok(可選,用于簡化實體類) -->  
<dependency>  <groupId>org.projectlombok</groupId>  <artifactId>lombok</artifactId>  <optional>true</optional>  
</dependency>

2. 配置數據庫

application.ymlapplication.properties中配置數據庫連接信息:

spring:  datasource:  url: jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC  username: root  password: your_password  driver-class-name: com.mysql.cj.jdbc.Driver  mybatis-plus:  mapper-locations: classpath:/mappers/*.xml  type-aliases-package: com.example.demo.entity  global-config:  db-config:  id-type: auto  logic-delete-value: 1  logic-not-delete-value: 0

3. 創建實體類

使用Lombok簡化代碼,例如:

import com.baomidou.mybatisplus.annotation.TableId;  
import com.baomidou.mybatisplus.annotation.TableName;  
import lombok.Data;  @Data  
@TableName("user")  
public class User {  @TableId  private Long id;  private String name;  private Integer age;  // 其他字段...  
}

4. 創建Mapper接口

繼承BaseMapper來簡化開發:

import com.baomidou.mybatisplus.core.mapper.BaseMapper;  
import com.example.demo.entity.User;  public interface UserMapper extends BaseMapper<User> {  // 這里可以添加自定義的Mapper方法,如果不需要可以留空  
}

5. 創建Service層

如果你需要,可以創建一個Service層來處理業務邏輯:

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;  
import com.example.demo.entity.User;  
import com.example.demo.mapper.UserMapper;  public class UserService extends ServiceImpl<UserMapper, User> {  // 這里可以添加自定義的業務邏輯方法  
}

6. 創建Controller層

創建RESTful API來處理HTTP請求:

import com.example.demo.entity.User;  
import com.example.demo.service.UserService;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.*;  @RestController  
@RequestMapping("/users")  
public class UserController {  @Autowired  private UserService userService;  @GetMapping("/")  public List<User> listAllUsers() {  return userService.list();  }  @PostMapping("/")  public User createUser(@RequestBody User user) {  userService.save(user);  return user;  }  @GetMapping("/{id}")  public User getUserById(@PathVariable Long id) {  return userService.getById(id);  }  @PutMapping("/{id}")  public User updateUser(@PathVariable Long id, @RequestBody User user) {  user.setId(id);  userService.updateById(user);  return user;  }

2、增加

import com.example.demo.entity.User;  
import com.example.demo.service.UserService;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.PostMapping;  
import org.springframework.web.bind.annotation.RequestBody;  
import org.springframework.web.bind.annotation.RestController;  @RestController  
@RequestMapping("/users")  
public class UserController {  @Autowired  private UserService userService;  @PostMapping("/")  public User createUser(@RequestBody User user) {  userService.save(user); // 調用Service層的save方法,實際調用的是MyBatis-Plus的插入操作  return user;  }  
}

3、刪除

// 刪除單個用戶  
@DeleteMapping("/{id}")  
public String deleteUser(@PathVariable Long id) {  userService.removeById(id); // 或者使用userMapper.deleteById(id)直接調用Mapper  return "User deleted successfully";  
}  // 批量刪除用戶(示例)  
@DeleteMapping("/batch")  
public String deleteUsers(@RequestBody List<Long> ids) {  userService.removeByIds(ids); // 批量刪除  return "Users deleted successfully";  
}

4、修改

// 更新用戶信息  
@PutMapping("/{id}")  
public User updateUser(@PathVariable Long id, @RequestBody User user) {  user.setId(id); // 確保用戶ID被設置  userService.updateById(user); // 調用Service層的updateById方法  return user;  
}

5、查找

// 查詢單個用戶  
@GetMapping("/{id}")  
public User getUserById(@PathVariable Long id) {  return userService.getById(id); // 調用Service層的getById方法  
}  // 查詢所有用戶  
@GetMapping("/")  
public List<User> getAllUsers() {  return userService.list(); // 調用Service層的list方法,實際調用的是MyBatis-Plus的查詢所有操作  
}  // 根據條件查詢用戶(示例,需要自定義Mapper或Service方法)  
@GetMapping("/search")  
public List<User> searchUsers(@RequestParam String name) {  // 這里僅為示例,實際中可能需要自定義Mapper接口中的方法  // return userService.searchByName(name); // 假設有這樣一個自定義方法  // ... 實際實現中,你可能需要編寫一個自定義的Mapper方法并使用@Select注解來定義SQL查詢  
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/39874.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/39874.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/39874.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

wordpress企業主題和wordpress免費主題

農業畜牧養殖wordpress主題 簡潔大氣的農業畜牧養殖wordpress主題&#xff0c;農業農村現代化&#xff0c;離不開新農人、新技術。 https://www.jianzhanpress.com/?p3051 SEO優化wordpress主題 簡潔的SEO優化wordpress主題&#xff0c;效果好不好&#xff0c;結果會告訴你…

JS中的上下文

一.執行上下文的概念&#xff1a; 執行上下文簡稱上下文。變量或者函數的上下文決定了它們可以訪問哪些數據&#xff0c;以及它們的行為。每一個上下文都具有一個關聯的變量對象&#xff0c;而這個上下文中定義的所有變量和函數都存在于這個對象上。 二.JS中上下文的執行機制&a…

第一后裔The First Descendant延遲、卡頓、無法聯機?

The First Descendant第一后裔游戲中還設計了多種輔助攻擊手段&#xff0c;它們如同角色手中的魔法&#xff0c;為戰斗增添了無數可能性。這些輔助攻擊手段或能造成范圍傷害&#xff0c;或能減速敵人&#xff0c;甚至能召喚出強大的支援力量。最近有玩家反映&#xff0c;遇到了…

Windows條件競爭提權漏洞復現(CVE-2024-300889)

漏洞原理 當內核將當前令牌對象的 _AUTHZBASEP_SECURITY_ATTRIBUTES_INFORMATION 復制到用戶模式時&#xff0c;錯誤位于函數 AuthzBasepCopyoutInternalSecurityAttributes 內部&#xff0c;該模式的結構如下&#xff1a; //0x30 bytes (sizeof) struct _AUTHZBASEP_SECURIT…

科研工具|從圖片中提取曲線數據

最近水哥在做一個項目時需要用到一篇論文中的數據&#xff0c;而這數據是作者的實驗數據&#xff0c;且年代較為久遠&#xff0c;聯系原作者要一份數據也不太現實&#xff0c;因而只能從論文的圖片中提取數據了。 目前市面上有很多小軟件可以實現這方面的功能&#xff0c;比如…

DVT:華為提出動態級聯Vision Transformer,性能杠杠的 | NeurIPS 2021

論文主要處理Vision Transformer中的性能問題&#xff0c;采用推理速度不同的級聯模型進行速度優化&#xff0c;搭配層級間的特征復用和自注意力關系復用來提升準確率。從實驗結果來看&#xff0c;性能提升不錯 來源&#xff1a;曉飛的算法工程筆記 公眾號 論文: Not All Image…

應用進程、SurfaceFlinger進程、HWC進程 之間的關系

應用進程、SurfaceFlinger進程、HWC&#xff08;Hardware Composer&#xff09;進程在Android系統中扮演著重要的角色&#xff0c;它們之間的關系和通信流程是Android圖形顯示系統的核心部分。以下是這三者之間關系和通信流程的詳細分析&#xff1a; 一、三者之間的關系 應用進…

AI 寫作:隨著互聯網的普及、人工智能的應用,越來越多的問題能很快得到答案。那么,我們的問題是否會越來越少?以上材料引發了你怎樣的聯想和思考?

隨著互聯網的迅速發展和人工智能技術的進步&#xff0c;信息獲取的速度和廣度都達到了前所未有的程度。人們只需輕點幾下鼠標或對著智能設備說出一句指令&#xff0c;海量的知識和解決方案就在眼前。這種便捷無疑極大地提高了我們的工作效率和生活質量&#xff0c;使我們在面對…

智慧應急管理平臺:數字孿生,讓防汛救災更科學高效

近期全國各地暴雨頻發&#xff0c;城市排水系統面臨著前所未有的挑戰&#xff0c;應急防澇已成為城市管理中不可或缺的一環。在這個信息化、智能化的時代&#xff0c;數字孿生技術以其獨特的優勢&#xff0c;為應急領域帶來了革命性的變革。數字孿生&#xff0c;作為現實世界在…

揭秘:學校教室采用數碼管同步時鐘的原因-訊鵬電子鐘

在學校的教室里&#xff0c;我們常常會看到數碼管同步時鐘的身影。究竟是什么原因讓它成為學校教室的寵兒呢&#xff1f;讓我們一同來探究其中的奧秘。 數碼管同步時鐘具有極高的準確性。對于學校這樣一個對時間管理要求嚴格的場所&#xff0c;準確的時間是保障教學秩序的基石。…

SwinIR: Image Restoration Using Swin Transformer(ICCV 2021)含代碼復現

目錄 一、Introduction 1 Motivation 2 Contribution 二、原理分析 1 Network Architecture 1&#xff09;Shallow feature extraction 2) deep feature extraction 3) image reconsruction modules 4) loss function 2 Residual Swin Transformer Block 三、實驗結果…

沒有調用memcpy卻報了undefined reference to memcpy錯誤

現象 在第5行出現了&#xff0c;undefined reference to memcpy’ 1 static void printf_x(unsigned int val) 2{ 3 char buffer[32]; 4 const char lut[]{0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F}; 5 char *p buffer; 6 while (val || p buffer) { 7 *(p) …

基于循環神經網絡的一維信號降噪方法(簡單版本,Python)

代碼非常簡單。 import torch import torch.nn as nn from torch.autograd import Variable from scipy.io.wavfile import write #need install pydub module #pip install pydub import numpy as np import pydub from scipy import signal import IPython import matplot…

C語言學習記錄(十二)——指針與數組及字符串

文章目錄 前言一、指針和數組二、指針和二維數組**行指針(數組指針)** 三、 字符指針和字符串四、指針數組 前言 一個學習嵌入式的小白~ 有問題評論區或私信指出~ 提示&#xff1a;以下是本篇文章正文內容&#xff0c;下面案例可供參考 一、指針和數組 在C語言中 &#xff0…

【vscode插件】多行注釋

最近在編寫C程序的過程中&#xff0c;筆者發現&#xff0c;vscode默認的多行注釋是使用單行注釋拼起來的&#xff0c;對于筆者想要突出多行注釋&#xff0c;同時便于后續修改的需求無法滿足&#xff0c;隨體驗一下自己開發VSCODE插件。 可以說&#xff0c;整個插件的開發和上線…

軟件開發生命周期(Software Development Life Cycle, SDLC)

目錄 簡介 簡介 軟件開發生命周期&#xff08;Software Development Life Cycle, SDLC&#xff09;是軟件從概念到正式交付和維護的一系列階段。每個階段都有其特定的目標和活動&#xff0c;以下是軟件開發生命周期中常見的幾個階段&#xff1a; 需求收集與分析&#xff08;R…

IndexError: image index out of range

IndexError: image index out of range 這個錯誤通常意味著你嘗試訪問的圖像索引超出了圖像的實際尺寸范圍。在你給出的代碼行&#xff1a; s_img_point_color_list.append(s_pixels[coordinate[0], coordinate[1]])你正在嘗試從 s_pixels 這個變量&#xff08;很可能是一個圖…

Android系統為什么lmkd殺到adj 100就代表有低內存?

在Android系統中&#xff0c;lmkd&#xff08;Low Memory Killer Daemon&#xff0c;低內存終止守護進程&#xff09;負責監控系統的內存狀態&#xff0c;并在內存壓力較高時通過終止不必要的進程來釋放內存&#xff0c;以維持系統的穩定運行。關于lmkd為何在殺到adj&#xff0…

Nginx負載均衡及動靜分離

目錄 一、Nginx負載均衡【重點】 1.1 輪詢 1.2 權重 1.3 ip_hash 二、Nginx動靜分離【重點】 2.1 動態資源代理 2.2 靜態資源代理 官方文檔 nginx 一、Nginx負載均衡【重點】 Nginx為我們默認提供了三種負載均衡的策略&#xff1a; 輪詢&#xff1a;將客戶端發起的請求…

【chatgpt】pytorch中requires_grad=True

在 PyTorch 中&#xff0c;requires_gradTrue 是一個非常重要的標志&#xff0c;它指示 PyTorch 是否需要為某個張量計算梯度。這在訓練神經網絡時尤為關鍵&#xff0c;因為我們通常需要通過反向傳播來更新模型參數&#xff0c;以最小化損失函數。 requires_gradTrue 的作用 …