Mybatis使用@one和@Many實現(xiàn)一對一及一對多關(guān)聯(lián)查詢
一、準備工作
1.創(chuàng)建springboot項目,項目結(jié)構(gòu)如下

2.添加pom.xml配置信息
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
</dependencies>
3.配置相關(guān)信息
將默認的application.properties文件的后綴修改為“.yml”,即配置文件名稱為:application.yml,并配置以下信息:
spring:
#DataSource數(shù)據(jù)源
datasource:
url: jdbc:mysql://localhost:3306/mybatis_test?useSSL=false&
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
#MyBatis配置
mybatis:
type-aliases-package: com.mye.hl07mybatis.api.pojo #別名定義
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #指定 MyBatis 所用日志的具體實現(xiàn),未指定時將自動查找
map-underscore-to-camel-case: true #開啟自動駝峰命名規(guī)則(camel case)映射
lazy-loading-enabled: true #開啟延時加載開關(guān)
aggressive-lazy-loading: false #將積極加載改為消極加載(即按需加載),默認值就是false
lazy-load-trigger-methods: "" #阻擋不相干的操作觸發(fā),實現(xiàn)懶加載
cache-enabled: true #打開全局緩存開關(guān)(二級環(huán)境),默認值就是true
二、使用@One注解實現(xiàn)一對一關(guān)聯(lián)查詢
需求:獲取用戶信息,同時獲取一對多關(guān)聯(lián)的權(quán)限列表
1.在MySQL數(shù)據(jù)庫中創(chuàng)建用戶信息表(tb_user)
-- 判斷數(shù)據(jù)表是否存在,存在則刪除
DROP TABLE IF EXISTS tb_user;
-- 創(chuàng)建“用戶信息”數(shù)據(jù)表
CREATE TABLE IF NOT EXISTS tb_user
(
user_id INT AUTO_INCREMENT PRIMARY KEY COMMENT '用戶編號',
user_account VARCHAR(50) NOT NULL COMMENT '用戶賬號',
user_password VARCHAR(50) NOT NULL COMMENT '用戶密碼',
blog_url VARCHAR(50) NOT NULL COMMENT '博客地址',
remark VARCHAR(50) COMMENT '備注'
) COMMENT = '用戶信息表';
-- 添加數(shù)據(jù)
INSERT INTO tb_user(user_account,user_password,blog_url,remark) VALUES('拒絕熬夜啊的博客','123456','https://blog.csdn.net/weixin_43296313/','您好,歡迎訪問拒絕熬夜啊的博客');
2.在MySQL數(shù)據(jù)庫中創(chuàng)建身份證信息表(tb_idcard)
-- 判斷數(shù)據(jù)表是否存在,存在則刪除 DROP TABLE IF EXISTS tb_idcard; -- 創(chuàng)建“身份證信息”數(shù)據(jù)表 CREATE TABLE IF NOT EXISTS tb_idcard ( id INT AUTO_INCREMENT PRIMARY KEY COMMENT '身份證ID', user_id INT NOT NULL COMMENT '用戶編號', idCard_code VARCHAR(45) COMMENT '身份證號碼' ) COMMENT = '身份證信息表'; -- 添加數(shù)據(jù) INSERT INTO tb_idcard(user_id,idCard_code) VALUE(1,'123456789');
3.創(chuàng)建用戶信息持久化類(UserInfo.java)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo {
private int userId; //用戶編號
private String userAccount; //用戶賬號
private String userPassword; //用戶密碼
private String blogUrl; //博客地址
private String remark; //備注
private IdcardInfo idcardInfo; //身份證信息
}
4.創(chuàng)建身份證信息持久化類(IdcardInfo.java)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class IdcardInfo {
public int id; //身份證ID
public int userId; //用戶編號
public String idCardCode; //身份證號碼
}
5.創(chuàng)建UserMapper接口(用戶信息Mapper動態(tài)代理接口)
@Repository
@Mapper
public interface UserMapper {
/**
* 獲取用戶信息和身份證信息
* 一對一關(guān)聯(lián)查詢
*/
@Select("SELECT * FROM tb_user WHERE user_id = #{userId}")
@Results(id = "userAndIdcardResultMap", value = {
@Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER, id = true),
@Result(property = "userAccount", column = "user_account",javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "userPassword", column = "user_password",javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "blogUrl", column = "blog_url",javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "remark", column = "remark",javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "idcardInfo",column = "user_id",
one = @One(select = "com.mye.hl07mybatis.api.mapper.UserMapper.getIdcardInfo", fetchType = FetchType.LAZY))
})
UserInfo getUserAndIdcardInfo(@Param("userId")int userId);
/**
* 根據(jù)用戶ID,獲取身份證信息
*/
@Select("SELECT * FROM tb_idcard WHERE user_id = #{userId}")
@Results(id = "idcardInfoResultMap", value = {
@Result(property = "id", column = "id"),
@Result(property = "userId", column = "user_id"),
@Result(property = "idCardCode", column = "idCard_code")})
IdcardInfo getIdcardInfo(@Param("userId")int userId);
}
6.實現(xiàn)實體類和數(shù)據(jù)表的映射關(guān)系
在SpringBoot啟動類中加 @MapperScan(basePackages = “com.mye.hl07mybatis.api.mapper”) 注解。
@SpringBootApplication
@MapperScan(basePackages = "com.mye.hl07mybatis.api.mapper")
public class Hl07MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(Hl07MybatisApplication.class, args);
}
}
7.編寫執(zhí)行方法,獲取用戶信息和身份證信息(一對一關(guān)聯(lián)查詢)
@SpringBootTest(classes = Hl07MybatisApplication.class)
@RunWith(SpringRunner.class)
public class Hl07MybatisApplicationTests {
@Autowired
private UserMapper userMapper;
/**
* 獲取用戶信息和身份證信息
* 一對一關(guān)聯(lián)查詢
* @author pan_junbiao
*/
@Test
public void getUserAndIdcardInfo() {
//執(zhí)行Mapper代理對象的查詢方法
UserInfo userInfo = userMapper.getUserAndIdcardInfo(1);
//打印結(jié)果
if(userInfo!=null) {
System.out.println("用戶編號:" + userInfo.getUserId());
System.out.println("用戶賬號:" + userInfo.getUserAccount());
System.out.println("用戶密碼:" + userInfo.getUserPassword());
System.out.println("博客地址:" + userInfo.getBlogUrl());
System.out.println("備注信息:" + userInfo.getRemark());
System.out.println("-----------------------------------------");
//獲取身份證信息
IdcardInfo idcardInfo = userInfo.getIdcardInfo();
if(idcardInfo!=null) {
System.out.println("身份證ID:" + idcardInfo.getId());
System.out.println("用戶編號:" + idcardInfo.getUserId());
System.out.println("身份證號碼:" + idcardInfo.getIdCardCode());
}
}
}
}
執(zhí)行結(jié)果:

三、使用@Many注解實現(xiàn)一對多關(guān)聯(lián)查詢
需求:獲取用戶信息,同時獲取一對多關(guān)聯(lián)的權(quán)限列表
1.在MySQL數(shù)據(jù)庫創(chuàng)建權(quán)限信息表(tb_role)
-- 判斷數(shù)據(jù)表是否存在,存在則刪除 DROP TABLE IF EXISTS tb_role; -- 創(chuàng)建“權(quán)限信息”數(shù)據(jù)表 CREATE TABLE IF NOT EXISTS tb_role ( id INT AUTO_INCREMENT PRIMARY KEY COMMENT '權(quán)限ID', user_id INT NOT NULL COMMENT '用戶編號', role_name VARCHAR(50) NOT NULL COMMENT '權(quán)限名稱' ) COMMENT = '權(quán)限信息表'; INSERT INTO tb_role(user_id,role_name) VALUES(1,'系統(tǒng)管理員'),(1,'新聞管理員'),(1,'廣告管理員');
2.創(chuàng)建權(quán)限信息持久化類(RoleInfo.java)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RoleInfo {
private int id; //權(quán)限ID
private int userId; //用戶編號
private String roleName; //權(quán)限名稱
}
3.修改用戶信息持久化類(UserInfo.java),添加權(quán)限列表的屬性字段
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo {
private int userId; //用戶編號
private String userAccount; //用戶賬號
private String userPassword; //用戶密碼
private String blogUrl; //博客地址
private String remark; //備注
private IdcardInfo idcardInfo; //身份證信息
private List<RoleInfo> roleInfoList; //權(quán)限列表
}
4.編寫用戶信息Mapper動態(tài)代理接口(UserMapper.java)
/**
* 獲取用戶信息和權(quán)限列表
* 一對多關(guān)聯(lián)查詢
* @author pan_junbiao
*/
@Select("SELECT * FROM tb_user WHERE user_id = #{userId}")
@Results(id = "userAndRolesResultMap", value = {
@Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER, id = true),
@Result(property = "userAccount", column = "user_account",javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "userPassword", column = "user_password",javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "blogUrl", column = "blog_url",javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "remark", column = "remark",javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "roleInfoList",column = "user_id", many = @Many(select = "com.pjb.mapper.UserMapper.getRoleList", fetchType = FetchType.LAZY))
})
public UserInfo getUserAndRolesInfo(@Param("userId")int userId);
/**
* 根據(jù)用戶ID,獲取權(quán)限列表
* @author pan_junbiao
*/
@Select("SELECT * FROM tb_role WHERE user_id = #{userId}")
@Results(id = "roleInfoResultMap", value = {
@Result(property = "id", column = "id"),
@Result(property = "userId", column = "user_id"),
@Result(property = "roleName", column = "role_name")})
public List<RoleInfo> getRoleList(@Param("userId")int userId);
5.編寫執(zhí)行方法,獲取用戶信息和權(quán)限列表(一對多關(guān)聯(lián)查詢)
/**
* 獲取用戶信息和權(quán)限列表
* 一對多關(guān)聯(lián)查詢
* @author pan_junbiao
*/
@Test
public void getUserAndRolesInfo() {
//執(zhí)行Mapper代理對象的查詢方法
UserInfo userInfo = userMapper.getUserAndRolesInfo(1);
//打印結(jié)果
if(userInfo!=null) {
System.out.println("用戶編號:" + userInfo.getUserId());
System.out.println("用戶賬號:" + userInfo.getUserAccount());
System.out.println("用戶密碼:" + userInfo.getUserPassword());
System.out.println("博客地址:" + userInfo.getBlogUrl());
System.out.println("備注信息:" + userInfo.getRemark());
System.out.println("-----------------------------------------");
//獲取權(quán)限列表
List<RoleInfo> roleInfoList = userInfo.getRoleInfoList();
if(roleInfoList!=null && roleInfoList.size()>0) {
System.out.println("用戶擁有的權(quán)限:");
for (RoleInfo roleInfo : roleInfoList) {
System.out.println(roleInfo.getRoleName());
}
}
}
}
執(zhí)行結(jié)果:

四、FetchType.LAZY 和 FetchType.EAGER的區(qū)別
FetchType.LAZY:懶加載,加載一個實體時,定義懶加載的屬性不會馬上從數(shù)據(jù)庫中加載。
FetchType.EAGER:急加載,加載一個實體時,定義急加載的屬性會立即從數(shù)據(jù)庫中加載。
到此這篇關(guān)于Mybatis使用@one和@Many實現(xiàn)一對一及一對多關(guān)聯(lián)查詢的文章就介紹到這了,更多相關(guān)Mybatis 一對一及一對多關(guān)聯(lián)查詢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Javaweb實戰(zhàn)之實現(xiàn)蛋糕訂購系統(tǒng)
隨著網(wǎng)絡的普及與發(fā)展,網(wǎng)上購物逐漸成為一種主流消費的方式。這篇文章主要介紹了通過JavaWeb制作一個線上蛋糕訂購系統(tǒng),文中示例代碼講解詳細,需要的朋友可以參考一下2021-12-12
Spring Security 技術(shù)原理與實戰(zhàn)全解析
SpringSecurity是Spring生態(tài)的安全框架,提供認證、授權(quán)、攻擊防護等功能,基于過濾器鏈和上下文模型,支持可插拔架構(gòu)與聲明式安全控制,適用于分布式和云原生場景,是Java應用安全的核心解決方案,本文給大家介紹Spring Security 原理實戰(zhàn),感興趣的朋友一起看看吧2025-06-06
SpringBoot使用除了Jasypt對YML文件配置內(nèi)容進行加密方式
文章介紹了如何在Java項目中使用Jasypt進行加密和解密,包括在pom.xml中添加依賴、在application.yml中配置信息、創(chuàng)建解密Bean以及確保秘鑰和算法的一致性2025-11-11
Java實現(xiàn)HTML轉(zhuǎn)為Word的示例代碼
本文以Java代碼為例為大家詳細介紹如何實現(xiàn)將HTML文件轉(zhuǎn)為Word文檔(.docx、.doc)。在實際開發(fā)場景中可參考此方法來轉(zhuǎn)換,感興趣的可以了解一下2022-06-06
SpringBoot+kaptcha實現(xiàn)驗證碼花式玩法詳解
這篇文章主要想和大家聊聊kaptcha的用法,畢竟這個已經(jīng)有16年歷史的玩意還在有人用,說明它的功能還是相當強大的,感興趣的小伙伴可以了解一下2022-05-05
Spring Boot 集成 ElasticSearch應用小結(jié)
這篇文章主要介紹了Spring Boot 集成 ElasticSearch應用小結(jié),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-11-11
SpringBoot整合liquibase及l(fā)iquibase生成初始化腳本的方式
這篇文章主要介紹了SpringBoot整合liquibase的相關(guān)資料,文中給大家介紹了liquibase生成初始化腳本的兩種方式,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-02-02

