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

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.配置相關信息
將默認的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 #開啟延時加載開關
aggressive-lazy-loading: false #將積極加載改為消極加載(即按需加載),默認值就是false
lazy-load-trigger-methods: "" #阻擋不相干的操作觸發(fā),實現(xiàn)懶加載
cache-enabled: true #打開全局緩存開關(二級環(huán)境),默認值就是true
二、使用@One注解實現(xiàn)一對一關聯(lián)查詢
需求:獲取用戶信息,同時獲取一對多關聯(liá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 {
/**
* 獲取用戶信息和身份證信息
* 一對一關聯(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ù)表的映射關系
在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í)行方法,獲取用戶信息和身份證信息(一對一關聯(lián)查詢)
@SpringBootTest(classes = Hl07MybatisApplication.class)
@RunWith(SpringRunner.class)
public class Hl07MybatisApplicationTests {
@Autowired
private UserMapper userMapper;
/**
* 獲取用戶信息和身份證信息
* 一對一關聯(lián)查詢
* @author pan_junbiao
*/
@Test
public void getUserAndIdcardInfo() {
//執(zhí)行Mapper代理對象的查詢方法
UserInfo userInfo = userMapper.getUserAndIdcardInfo(1);
//打印結果
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í)行結果:

三、使用@Many注解實現(xiàn)一對多關聯(lián)查詢
需求:獲取用戶信息,同時獲取一對多關聯(lián)的權限列表
1.在MySQL數(shù)據(jù)庫創(chuàng)建權限信息表(tb_role)
-- 判斷數(shù)據(jù)表是否存在,存在則刪除 DROP TABLE IF EXISTS tb_role; -- 創(chuàng)建“權限信息”數(shù)據(jù)表 CREATE TABLE IF NOT EXISTS tb_role ( id INT AUTO_INCREMENT PRIMARY KEY COMMENT '權限ID', user_id INT NOT NULL COMMENT '用戶編號', role_name VARCHAR(50) NOT NULL COMMENT '權限名稱' ) COMMENT = '權限信息表'; INSERT INTO tb_role(user_id,role_name) VALUES(1,'系統(tǒng)管理員'),(1,'新聞管理員'),(1,'廣告管理員');
2.創(chuàng)建權限信息持久化類(RoleInfo.java)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RoleInfo {
private int id; //權限ID
private int userId; //用戶編號
private String roleName; //權限名稱
}
3.修改用戶信息持久化類(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; //身份證信息
private List<RoleInfo> roleInfoList; //權限列表
}
4.編寫用戶信息Mapper動態(tài)代理接口(UserMapper.java)
/**
* 獲取用戶信息和權限列表
* 一對多關聯(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,獲取權限列表
* @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í)行方法,獲取用戶信息和權限列表(一對多關聯(lián)查詢)
/**
* 獲取用戶信息和權限列表
* 一對多關聯(lián)查詢
* @author pan_junbiao
*/
@Test
public void getUserAndRolesInfo() {
//執(zhí)行Mapper代理對象的查詢方法
UserInfo userInfo = userMapper.getUserAndRolesInfo(1);
//打印結果
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("-----------------------------------------");
//獲取權限列表
List<RoleInfo> roleInfoList = userInfo.getRoleInfoList();
if(roleInfoList!=null && roleInfoList.size()>0) {
System.out.println("用戶擁有的權限:");
for (RoleInfo roleInfo : roleInfoList) {
System.out.println(roleInfo.getRoleName());
}
}
}
}
執(zhí)行結果:

四、FetchType.LAZY 和 FetchType.EAGER的區(qū)別
FetchType.LAZY:懶加載,加載一個實體時,定義懶加載的屬性不會馬上從數(shù)據(jù)庫中加載。
FetchType.EAGER:急加載,加載一個實體時,定義急加載的屬性會立即從數(shù)據(jù)庫中加載。
到此這篇關于Mybatis使用@one和@Many實現(xiàn)一對一及一對多關聯(lián)查詢的文章就介紹到這了,更多相關Mybatis 一對一及一對多關聯(lián)查詢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring boot @ModelAttribute標注的實現(xiàn)
這篇文章主要介紹了Spring boot @ModelAttribute標注的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-01-01
Spring Boot多模塊化后,服務間調(diào)用的坑及解決
這篇文章主要介紹了Spring Boot多模塊化后,服務間調(diào)用的坑及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
mybatis 使用jdbc.properties文件設置不起作用的解決方法
這篇文章主要介紹了mybatis 使用jdbc.properties文件設置不起作用的解決方法,需要的朋友可以參考下2018-03-03
Java使用openssl檢測網(wǎng)站是否支持ocsp
OCSP在線證書狀態(tài)協(xié)議是為了替換CRL而提出來的。對于現(xiàn)代web服務器來說一般都是支持OCSP的,OCSP也是現(xiàn)代web服務器的標配,這篇文章主要介紹了Java使用openssl檢測網(wǎng)站是否支持ocsp,需要的朋友可以參考下2022-07-07
SpringCloud項目中Feign組件添加請求頭所遇到的坑及解決
這篇文章主要介紹了SpringCloud項目中Feign組件添加請求頭所遇到的坑及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
java實現(xiàn)附件預覽(openoffice+swftools+flexpaper)實例
本篇文章主要介紹了java實現(xiàn)附件預覽(openoffice+swftools+flexpaper)實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2016-10-10

