Mybatis使用@one和@Many實(shí)現(xiàn)一對一及一對多關(guān)聯(lián)查詢
一、準(zhǔn)備工作
1.創(chuàng)建springboot項(xiàng)目,項(xiàng)目結(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)信息
將默認(rè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 所用日志的具體實(shí)現(xiàn),未指定時(shí)將自動(dòng)查找
map-underscore-to-camel-case: true #開啟自動(dòng)駝峰命名規(guī)則(camel case)映射
lazy-loading-enabled: true #開啟延時(shí)加載開關(guān)
aggressive-lazy-loading: false #將積極加載改為消極加載(即按需加載),默認(rèn)值就是false
lazy-load-trigger-methods: "" #阻擋不相干的操作觸發(fā),實(shí)現(xiàn)懶加載
cache-enabled: true #打開全局緩存開關(guān)(二級環(huán)境),默認(rèn)值就是true
二、使用@One注解實(shí)現(xiàn)一對一關(guān)聯(lián)查詢
需求:獲取用戶信息,同時(shí)獲取一對多關(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 '用戶編號(hào)',
user_account VARCHAR(50) NOT NULL COMMENT '用戶賬號(hào)',
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 '用戶編號(hào)', idCard_code VARCHAR(45) COMMENT '身份證號(hào)碼' ) 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; //用戶編號(hào)
private String userAccount; //用戶賬號(hào)
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; //用戶編號(hào)
public String idCardCode; //身份證號(hào)碼
}
5.創(chuàng)建UserMapper接口(用戶信息Mapper動(dòng)態(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.實(shí)現(xiàn)實(shí)體類和數(shù)據(jù)表的映射關(guān)系
在SpringBoot啟動(dòng)類中加 @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("用戶編號(hào):" + userInfo.getUserId());
System.out.println("用戶賬號(hào):" + 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("用戶編號(hào):" + idcardInfo.getUserId());
System.out.println("身份證號(hào)碼:" + idcardInfo.getIdCardCode());
}
}
}
}
執(zhí)行結(jié)果:

三、使用@Many注解實(shí)現(xiàn)一對多關(guān)聯(lián)查詢
需求:獲取用戶信息,同時(shí)獲取一對多關(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 '用戶編號(hào)', 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; //用戶編號(hào)
private String roleName; //權(quán)限名稱
}
3.修改用戶信息持久化類(UserInfo.java),添加權(quán)限列表的屬性字段
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo {
private int userId; //用戶編號(hào)
private String userAccount; //用戶賬號(hào)
private String userPassword; //用戶密碼
private String blogUrl; //博客地址
private String remark; //備注
private IdcardInfo idcardInfo; //身份證信息
private List<RoleInfo> roleInfoList; //權(quán)限列表
}
4.編寫用戶信息Mapper動(dòng)態(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("用戶編號(hào):" + userInfo.getUserId());
System.out.println("用戶賬號(hào):" + 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:懶加載,加載一個(gè)實(shí)體時(shí),定義懶加載的屬性不會(huì)馬上從數(shù)據(jù)庫中加載。
FetchType.EAGER:急加載,加載一個(gè)實(shí)體時(shí),定義急加載的屬性會(huì)立即從數(shù)據(jù)庫中加載。
到此這篇關(guān)于Mybatis使用@one和@Many實(shí)現(xiàn)一對一及一對多關(guān)聯(lián)查詢的文章就介紹到這了,更多相關(guān)Mybatis 一對一及一對多關(guān)聯(lián)查詢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Mybatis中一對多(collection)和一對一(association)的組合查詢使用
- Mybatis實(shí)現(xiàn)一對一、一對多關(guān)聯(lián)查詢的方法(示例詳解)
- 關(guān)于mybatis一對一查詢一對多查詢遇到的問題
- springboot整合mybatis-plus基于注解實(shí)現(xiàn)一對一(一對多)查詢功能
- mybatis 一對一、一對多和多對多查詢實(shí)例代碼
- Mybatis 中的一對一,一對多,多對多的配置原則示例代碼
- Mybatis中的高級映射一對一、一對多、多對多
- mybatis中一對一、一對多的<association> 配置使用
相關(guān)文章
Java實(shí)現(xiàn)布隆過濾器的幾種方式總結(jié)
這篇文章給大家總結(jié)了幾種Java實(shí)現(xiàn)布隆過濾器的方式,手動(dòng)硬編碼實(shí)現(xiàn),引入Guava實(shí)現(xiàn),引入hutool實(shí)現(xiàn),通過redis實(shí)現(xiàn)等幾種方式,文中有詳細(xì)的代碼和圖解,需要的朋友可以參考下2023-07-07
Spring boot @ModelAttribute標(biāo)注的實(shí)現(xiàn)
這篇文章主要介紹了Spring boot @ModelAttribute標(biāo)注的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01
Spring Boot多模塊化后,服務(wù)間調(diào)用的坑及解決
這篇文章主要介紹了Spring Boot多模塊化后,服務(wù)間調(diào)用的坑及解決,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Java通過索引值實(shí)現(xiàn)約瑟夫環(huán)算法
這篇文章主要介紹了Java通過索引值實(shí)現(xiàn)約瑟夫環(huán),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05
mybatis 使用jdbc.properties文件設(shè)置不起作用的解決方法
這篇文章主要介紹了mybatis 使用jdbc.properties文件設(shè)置不起作用的解決方法,需要的朋友可以參考下2018-03-03
Java使用openssl檢測網(wǎng)站是否支持ocsp
OCSP在線證書狀態(tài)協(xié)議是為了替換CRL而提出來的。對于現(xiàn)代web服務(wù)器來說一般都是支持OCSP的,OCSP也是現(xiàn)代web服務(wù)器的標(biāo)配,這篇文章主要介紹了Java使用openssl檢測網(wǎng)站是否支持ocsp,需要的朋友可以參考下2022-07-07
Springboot如何優(yōu)雅的關(guān)閉應(yīng)用
這篇文章主要介紹了Springboot如何優(yōu)雅的關(guān)閉應(yīng)用問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
SpringCloud項(xiàng)目中Feign組件添加請求頭所遇到的坑及解決
這篇文章主要介紹了SpringCloud項(xiàng)目中Feign組件添加請求頭所遇到的坑及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04
java實(shí)現(xiàn)附件預(yù)覽(openoffice+swftools+flexpaper)實(shí)例
本篇文章主要介紹了java實(shí)現(xiàn)附件預(yù)覽(openoffice+swftools+flexpaper)實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2016-10-10
一篇超詳細(xì)的Spring Boot整合Mybatis文章
大家都知道springboot搭建一個(gè)spring框架只需要秒秒鐘。下面通過實(shí)例代碼給大家介紹一下springboot與mybatis的完美融合,非常不錯(cuò),具有參考借鑒價(jià)值,感興趣的朋友一起看看吧2021-07-07

