当前位置: 首页 > java >正文

【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.xdnf.cn/news/1200.html

相关文章:

  • 权限管理降维打击:AI自动生成分布式系统鉴权代码(含JWT刷新策略)
  • 如何通过证书认证安全登录堡垒机、防火墙和VPN?安当KSP密钥管理系统助力企业实现零信任身份验证
  • 【中级软件设计师】程序设计语言基础成分
  • 3.1.2 materialDesign:Card 的使用介绍
  • VUE篇之,实现锚点定位,滚动与导航联动
  • 黑盒测试——等价类划分法实验
  • 虚拟机超详细Ubuntu安装教程
  • 测试基础笔记第九天
  • Idea创建项目的搭建
  • Git入门
  • 从 0 到 1 打通 AI 工作流:Dify+Zapier 实现工具自动化调用实战
  • 进阶篇 第 3 篇:经典永不落幕 - ARIMA 模型详解与实践
  • 乐视系列玩机---乐视2 x520 x528等系列线刷救砖以及刷写第三方twrp 卡刷第三方固件步骤解析
  • EAL4+与等保2.0:解读中国网络安全双标准
  • 【深度学习】LoRA:低秩适应性微调技术详解
  • 【数学建模】孤立森林算法:异常检测的高效利器
  • NDSS 2025|侧信道与可信计算攻击技术导读(二)系统化评估新旧缓存侧信道攻击技术
  • YOLO-E:详细信息
  • 【机器学习案列-21】基于 LightGBM 的智能手机用户行为分类
  • 2022年全国职业院校技能大赛 高职组 “大数据技术与应用” 赛项赛卷(10卷)任务书
  • jenkins pipeline ssh协议报错处理
  • 多模态模型实现原理详细介绍
  • Python 设计模式:模板模式
  • FastText 模型文本分类实验:从零到一的实战探索
  • 4.22tx视频后台开发一面
  • JAVA:Web安全防御
  • 考研系列-计算机网络-第五章、传输层
  • 什么是CRM系统,它的作用是什么?CRM全面指南
  • 信奥赛CSP-J复赛集训(DP专题)(19):P3399 丝绸之路
  • 基于51单片机的温度控制系统proteus仿真