【Spring Boot】MyBatis多表查詢的操作:注解和XML實現SQL語句

1.準備工作

1.1創建數據庫

(1)創建數據庫:

CREATE DATABASE mybatis_test DEFAULT CHARACTER SET utf8mb4;

(2)使用數據庫

-- 使?數據數據
USE mybatis_test;

1.2 創建用戶表和實體類

創建用戶表


-- 創建表[??表]CREATE TABLE `user_info` (`id` INT ( 11 ) NOT NULL AUTO_INCREMENT,`username` VARCHAR ( 127 ) NOT NULL,`password` VARCHAR ( 127 ) NOT NULL,`age` TINYINT ( 4 ) NOT NULL,`gender` TINYINT ( 4 ) DEFAULT '0' COMMENT '1-男 2-? 0-默認',`phone` VARCHAR ( 15 ) DEFAULT NULL,`delete_flag` TINYINT ( 4 ) DEFAULT 0 COMMENT '0-正常, 1-刪除',`create_time` DATETIME DEFAULT now(),`update_time` DATETIME DEFAULT now() ON UPDATE now(),PRIMARY KEY ( `id` ) 
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4; 

添加用戶信息

-- 添加??信息
INSERT INTO user_info( username, `password`, age, gender, phone )
VALUES ( 'admin', 'admin', 18, 1, '18612340001' );
INSERT INTO user_info( username, `password`, age, gender, phone )
VALUES ( 'zhangsan', 'zhangsan', 18, 1, '18612340002' );
INSERT INTO user_info( username, `password`, age, gender, phone )
VALUES ( 'lisi', 'lisi', 18, 1, '18612340003' );
INSERT INTO user_info( username, `password`, age, gender, phone )
VALUES ( 'wangwu', 'wangwu', 18, 1, '18612340004' );

實體類的屬性名與表中的字段名??對應

@Data
public class UserInfo {private Integer id;private String username;private String password;private Integer age;private Integer gender;private String phone;private Integer deleteFlag;private Date createTime;private Date updateTime;}

1.3 創建文章表和實體類

上?建了?張??表, 我們再來建?張?章表, 進?多表關聯查詢.
?章表的uid, 對應??表的id.

創建文章表:

-- 創建?章表
DROP TABLE IF EXISTS articleinfo;
CREATE TABLE articleinfo (
id INT PRIMARY KEY auto_increment, title VARCHAR ( 100 ) NOT NULL,
content TEXT NOT NULL, uid INT NOT NULL,
delete_flag TINYINT ( 4 ) DEFAULT 0 COMMENT '0-正常, 1-刪除',
create_time DATETIME DEFAULT now(), update_time DATETIME DEFAULT now()
) DEFAULT charset 'utf8mb4';

插入數據

-- 插?測試數據
INSERT INTO articleinfo ( title, content, uid ) VALUES ( 'Java', 'Java正文', 1
);
INSERT INTO articleinfo ( title, content, uid ) VALUES ( 'MySQL', 'MySQL正文', 1
);
INSERT INTO articleinfo ( title, content, uid ) VALUES ( 'C', 'C正文', 2
);

實體類的屬性名與表中的字段名??對應

@Data
public class ArticleInfo { private Integer id; private String title; private String content; private Integer uid; private Integer deleteFlag; private Date createTime; private Date updateTime;
}

1.4 配置文件

Application.yml文件中配置:

# 數據庫連接配置
spring:datasource:# MySQL在遠程服務器上url: jdbc:mysql://x.x.x.x:3306/mybatis_test?characterEncoding=utf8&useSSL=falseusername: root  #MySQL賬號password: root  #MySQL密碼driver-class-name: com.mysql.cj.jdbc.Drivermybatis:configuration: # 配置打印 MyBatis?志log-impl: org.apache.ibatis.logging.stdout.StdOutImplmap-underscore-to-camel-case: true #配置駝峰?動轉換# 配置 mybatis xml 的?件路徑,在 resources/mapper 創建所有表的 xml ?件mapper-locations: classpath:mapper/**Mapper.xml

2.多表查詢

2.1 需求: 根據uid查詢書的作者等相關信息

2.1.1 注解實現

SQL命令:

SELECTa.id,a.title,a.content,a.uid,b.username,b.age,b.gender
FROMarticleinfo aLEFT JOIN user_info b ON a.uid = b.id
WHEREa.id =1;

根據查詢的結果在ArticleInfo 類補充相關的屬性:

@Data
public class ArticleInfo {private Integer id;private String title;private String content;private Integer uid;private Integer deleteFlag;private Date createTime;private Date updateTime;// 補充??相關信息private String username;private Integer age;private Integer gender;}

ArticleInfoMapper接口:

@Mapper
public interface ArticleInfoMapper {@Select("select a.id,a.title,a.content,a.uid, b.username, b.age, b.gender " + // 注意最后的空格"from articleinfo a left join user_info b on a.uid=b.id " +"where a.id = #{id}")ArticleInfo queryArticleAndUser(Integer id);
}

測試代碼:

@Slf4j
@SpringBootTest
class ArticleInfoMapperTest {@Autowiredprivate ArticleInfoMapper articleInfoMapper;@Testvoid queryArticleAndUser() {articleInfoMapper.queryArticleAndUser(1);}
}

運行結果:
在這里插入圖片描述
如果名稱不?致的, 采?Results, 或者別名的?式解決, 和單表查詢?樣 Mybatis 不分單表還是多表, 主要就是三部分: SQL, 映射關系和實體類

2.1.2 XML實現

SQL命令:

SELECTa.id,a.title,a.content,a.uid,b.username,b.age,b.gender
FROMarticleinfo aLEFT JOIN user_info b ON a.uid = b.id
WHEREa.id =1;

根據查詢的結果在ArticleInfo 類補充相關的屬性:

@Data
public class ArticleInfo {private Integer id;private String title;private String content;private Integer uid;private Integer deleteFlag;private Date createTime;private Date updateTime;// 補充??相關信息private String username;private Integer age;private Integer gender;}

ArticleInfoMapper接口:

@Mapper
public interface ArticleInfoXMLMapper {ArticleInfo queryArticleAndUser(Integer id);
}

ArticleInfoXMLMapper.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="org.example.mybatis.mapper.ArticleInfoXMLMapper"><select id ="queryArticleAndUser" resultType="org.example.mybatis.model.ArticleInfo">select a.id,a.title,a.content,a.uid, b.username, b.age, b.genderfrom articleinfo a left join user_info b on a.uid=b.idwhere a.id = #{id}</select></mapper>

測試代碼:

@Slf4j
@SpringBootTest
class ArticleInfoXMLMapperTest {@Autowiredprivate ArticleInfoXMLMapper articleInfoXMLMapper;@Testvoid queryArticleAndUser() {articleInfoXMLMapper.queryArticleAndUser(1);}
}

運行結果:
在這里插入圖片描述

如果名稱不?致的, 采?ResultMap, 或者別名的?式解決, 和單表查詢?樣 Mybatis 不分單表還是多表, 主要就是三部分: SQL, 映射關系和實體類

2.2 需求: 根據user_in的id查詢作者創作的書相關信息

2.1.1 注解實現

SQL命令:

SELECTb.username,b.age,b.gender,a.id,a.title,a.content,a.uid
FROMarticleinfo aRIGTH JOIN user_info  b ON b.uid = a.id
WHEREb.id =1;

根據查詢的結果在ArticleInfo 類補充相關的屬性:

@Data
public class ArticleInfo {private Integer id;private String title;private String content;private Integer uid;private Integer deleteFlag;private Date createTime;private Date updateTime;// 補充??相關信息private String username;private Integer age;private Integer gender;}

ArticleInfoMapper接口:

@Mapper
public interface ArticleInfoMapper {@Select("select b.username, b.age,b.gender,a.id,a.title,a.content,a.uid " + // 注意最后的空格"from articleinfo a right join user_info b on a.uid=b.id " +"where b.id = #{id}")List<ArticleInfo> queryArticleAndUser(Integer id);
}

測試代碼:

@Slf4j
@SpringBootTest
class ArticleInfoMapperTest {@Autowiredprivate ArticleInfoMapper articleInfoMapper;@Testvoid queryArticleAndUser() {articleInfoMapper.queryArticleAndUser(1);}
}

運行結果:
在這里插入圖片描述

如果名稱不?致的, 采?Results, 或者別名的?式解決, 和單表查詢?樣 Mybatis 不分單表還是多表, 主要就是三部分: SQL, 映射關系和實體類

2.1.2 XML實現

SQL命令:

SELECTb.username,b.age,b.gender,a.id,a.title,a.content,a.uid
FROMarticleinfo aRIGHT JOIN user_info b ON a.uid = b.id
WHEREa.id =1;

根據查詢的結果在ArticleInfo 類補充相關的屬性:

@Data
public class ArticleInfo {private Integer id;private String title;private String content;private Integer uid;private Integer deleteFlag;private Date createTime;private Date updateTime;// 補充??相關信息private String username;private Integer age;private Integer gender;}

ArticleInfoMapper接口:

@Mapper
public interface ArticleInfoXMLMapper {List<ArticleInfo> queryArticleAndUser(Integer id);
}

ArticleInfoXMLMapper.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="org.example.mybatis.mapper.ArticleInfoXMLMapper"><select id ="queryArticleAndUser" resultType="org.example.mybatis.model.ArticleInfo">select b.username, b.age, b.gender,a.id,a.title,a.content,a.uidfrom articleinfo a right join user_info b on a.uid=b.idwhere b.id = #{id}</select></mapper>

測試代碼:

@Slf4j
@SpringBootTest
class ArticleInfoXMLMapperTest {@Autowiredprivate ArticleInfoXMLMapper articleInfoXMLMapper;@Testvoid queryArticleAndUser() {articleInfoXMLMapper.queryArticleAndUser(1);}
}

運行結果:
在這里插入圖片描述

如果名稱不?致的, 采?ResultMap, 或者別名的?式解決, 和單表查詢?樣 Mybatis 不分單表還是多表, 主要就是三部分: SQL, 映射關系和實體類

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

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

相關文章

ISO15189認證有什么要求?ISO15189認證流程

ISO 15189 認證要求及流程詳解 ISO 15189 是國際標準化組織&#xff08;ISO&#xff09;針對 醫學實驗室質量和能力 的認證標準&#xff0c;適用于醫院檢驗科、第三方醫學實驗室、血站等機構。該認證確保實驗室的技術能力和管理體系符合國際標準&#xff0c;提高檢測結果的準確…

【Linux】調試工具gdb的認識和使用指令介紹(圖文詳解)

目錄 1、debug和release的知識 2、gdb的使用和常用指令介紹&#xff1a; &#xff08;1&#xff09;、windows下調試的功能&#xff1a; &#xff08;2&#xff09;、進入和退出&#xff1a; &#xff08;3&#xff09;、調試過程中的相關指令&#xff1a; 3、調試究竟是在…

【Pytorch 中的擴散模型】去噪擴散概率模型(DDPM)的實現

介紹 廣義上講&#xff0c;擴散模型是一種生成式深度學習模型&#xff0c;它通過學習到的去噪過程來創建數據。擴散模型有很多變體&#xff0c;其中最流行的通常是文本條件模型&#xff0c;它可以根據提示生成特定的圖像。一些擴散模型&#xff08;例如 Control-Net&#xff0…

Milvus(3):數據庫、Collections說明

1 數據庫 Milvus 在集合之上引入了數據庫層&#xff0c;為管理和組織數據提供了更有效的方式&#xff0c;同時支持多租戶。 1.1 什么是數據庫 在 Milvus 中&#xff0c;數據庫是組織和管理數據的邏輯單元。為了提高數據安全性并實現多租戶&#xff0c;你可以創建多個數據庫&am…

【質量管理】“武藏曲線”和“微笑曲線”的差異

什么是“微笑曲線” 在電子制造領域&#xff0c;“微笑曲線”&#xff08;Smiling Curve&#xff09;是由宏碁集團創始人施振榮于1992年提出的一個理論模型&#xff0c;用于描述產業鏈中不同環節的附加價值分布。該曲線因形狀類似“微笑”而得名&#xff0c;核心觀點是&#xf…

【html】a標簽target屬性以及擴展應用

進行頁面新窗口打開跳轉&#xff0c;我們使用 <a> 標簽即可實現。 <a>標簽可以通過設置target的值來控制此鏈接的打開方式&#xff0c;一般可取以下值&#xff1a; _self&#xff1a;默認值&#xff0c;鏈接在當前窗口打開 _blank&#xff1a;鏈接在新窗口打開 …

一文讀懂什么是 MCP、A2A、ANP

在人工智能快速發展的今天&#xff0c;智能體&#xff08;Agent&#xff09;正逐步成為互聯網交互的新主體。它們不僅能替代人類完成復雜任務&#xff0c;還能通過協作形成更高效的網絡生態。然而&#xff0c;這一切的實現離不開通信協議的支持。本文將解析智能體領域的三大核心…

Python3網絡爬蟲開發--爬蟲基礎

網絡爬蟲基礎 1.1 HTTP基本原理 1.1.1 URI和URL URI即統一資源標志符,URL即統一資源定位符。 有這樣一個鏈接,http://test.com/test.txt,在這個鏈接中,包含了訪問協議https,訪問目錄(即根目錄),資源名稱(test.txt)。通過這樣的鏈接,可以在互聯網上找到這個資源,這…

OpenCV顏色變換cvtColor

OpenCV計算機視覺開發實踐&#xff1a;基于Qt C - 商品搜索 - 京東 顏色變換是imgproc模塊中一個常用的功能。我們生活中看到的大多數彩色圖片都是RGB類型的&#xff0c;但是在進行圖像處理時需要用到灰度圖、二值圖、HSV&#xff08;六角錐體模型&#xff0c;這個模型中顏色的…

Hadoop----高可用搭建

目錄標題 **什么是高可用&#xff1f;****?搭建的步驟**一.jdk**安裝配置**- **要點**: 二.zookeeper**集群配置**- **要點** 三.Hadoop高可用的搭建- **要點**①環境變量的配置②配置文件的修改 ③內容分發④集群任務的初次啟動 什么是高可用&#xff1f; 通過冗余設計 自動…

【Rust 精進之路之第15篇-枚舉 Enum】定義、變體與數據關聯:表達多種可能性

系列: Rust 精進之路:構建可靠、高效軟件的底層邏輯 作者: 碼覺客 發布日期: 2025年4月20日 引言:當值擁有“選項”——超越結構體的表達力 在上一篇【結構體 Struct】中,我們學習了如何使用結構體將多個相關的數據字段組合成一個有意義的整體。結構體非常適合表示那些…

模擬實現strncat、qsort、atoi

目錄 前言 一、模擬實現strncat 參數 代碼演示&#xff1a; 二、模擬實現qsort 參數 代碼演示&#xff1a; 前言 本文主要是對strncat&#xff0c;qsort&#xff0c;atoi的模擬實現 一、模擬實現strncat C 庫函數 char *strncat(char *dest, const char *src, size_t n…

Ubuntu 系統中修改 MySQL 的 sql_mode

在 Ubuntu 系統中修改 MySQL 的 sql_mode 需要編輯 MySQL 的配置文件并重啟服務。以下是詳細步驟&#xff1a; 步驟 1&#xff1a;定位 MySQL 配置文件 MySQL 配置文件通常位于以下路徑之一&#xff08;具體取決于安裝方式&#xff09;&#xff1a; /etc/mysql/my.cnf /etc/m…

進階算法 第一課:貪心

本文遵循 CC BY-NC-ND 4.0 協議&#xff0c;作者&#xff1a; U?ェ?*U \texttt{U?ェ?*U} U?ェ?*U&#xff0c;轉載請獲得作者授權。 歡迎大家來到進階算法第一課&#xff1a;貪心&#xff1b;我會分為以下幾點為大家講解貪心&#xff1a; 什么是貪心。貪心的性質與分類。…

AI領域:MCP 與 A2A 協議的關系

一、為何會出現MCP和A2A 協議是非常重要的東西&#xff0c;只有大家都遵循統一的協議&#xff0c;整體生態才好發展&#xff0c;正如有了HTML&#xff0c;互聯網才快速發展&#xff0c;有了OpenAPI&#xff0c; API才會快速發展。 Agent目前是發展最快的領域&#xff0c;從最初…

深度學習訓練中的顯存溢出問題分析與優化:以UNet圖像去噪為例

最近在訓練一個基于 Tiny-UNet 的圖像去噪模型時&#xff0c;我遇到了經典但棘手的錯誤&#xff1a; RuntimeError: CUDA out of memory。本文記錄了我如何從復現、分析&#xff0c;到逐步優化并成功解決該問題的全過程&#xff0c;希望對深度學習開發者有所借鑒。 訓練數據&am…

FramePack V2版 - 支持首尾幀生成,支持LoRA,支持批量,支持50系顯卡,一個強大的AI視頻生成軟件 本地一鍵整合包下載

FramePack 是斯坦福大學主導開發的視頻生成框架&#xff0c;是一種用于視頻生成的下一幀&#xff08;下一幀部分&#xff09;預測神經網絡結構&#xff0c;可以逐步生成視頻。FramePack 主要開發者之一&#xff0c;就是業內大名鼎鼎的張呂敏大佬&#xff0c;AI領域的“賽博佛祖…

STM32 HAL 通用定時器延時函數

使用通用定時器TIM3&#xff0c;實現ms、us延時。 delay.c #include "delay.h" #include "stm32f1xx_hal.h"TIM_HandleTypeDef htim3;/*** brief 初始化定時器3用于延時* param 無* retval 無*/ void Delay_Init(void) {TIM_ClockConfigTypeDef sClock…

軟件功能測試和非功能測試有什么區別和聯系?

軟件測試是保障軟件質量的核心環節&#xff0c;而軟件功能測試和非功能測試作為測試領域的兩大重要組成部分&#xff0c;承擔著不同但又相互關聯的職責。 軟件功能測試指的是通過驗證軟件系統的各項功能是否按照需求規格說明書來正確實現&#xff0c;確保軟件的功能和業務流程…

使用Java調用TensorFlow與PyTorch模型:DJL框架的應用探索

在現代機器學習的應用場景中&#xff0c;Python早已成為廣泛使用的語言&#xff0c;尤其是在深度學習框架TensorFlow和PyTorch的開發和應用中。盡管Java在許多企業級應用中占據一席之地&#xff0c;但因為缺乏直接使用深度學習框架的能力&#xff0c;往往使得Java開發者對機器學…