Mybatis使用@one和@Many實現一對一及一對多關聯查詢
一、準備工作
1.創建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數據源 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 所用日志的具體實現,未指定時將自動查找 map-underscore-to-camel-case: true #開啟自動駝峰命名規則(camel case)映射 lazy-loading-enabled: true #開啟延時加載開關 aggressive-lazy-loading: false #將積極加載改為消極加載(即按需加載),默認值就是false lazy-load-trigger-methods: "" #阻擋不相幹的操作觸發,實現懶加載 cache-enabled: true #打開全局緩存開關(二級環境),默認值就是true
二、使用@One註解實現一對一關聯查詢
需求:獲取用戶信息,同時獲取一對多關聯的權限列表
1.在MySQL數據庫中創建用戶信息表(tb_user)
-- 判斷數據表是否存在,存在則刪除 DROP TABLE IF EXISTS tb_user; -- 創建“用戶信息”數據表 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 = '用戶信息表'; -- 添加數據 INSERT INTO tb_user(user_account,user_password,blog_url,remark) VALUES('拒絕熬夜啊的博客','123456','https://blog.csdn.net/weixin_43296313/','您好,歡迎訪問拒絕熬夜啊的博客');
2.在MySQL數據庫中創建身份證信息表(tb_idcard)
-- 判斷數據表是否存在,存在則刪除 DROP TABLE IF EXISTS tb_idcard; -- 創建“身份證信息”數據表 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 = '身份證信息表'; -- 添加數據 INSERT INTO tb_idcard(user_id,idCard_code) VALUE(1,'123456789');
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; //身份證信息 }
4.創建身份證信息持久化類(IdcardInfo.java)
@Data @AllArgsConstructor @NoArgsConstructor public class IdcardInfo { public int id; //身份證ID public int userId; //用戶編號 public String idCardCode; //身份證號碼 }
5.創建UserMapper接口(用戶信息Mapper動態代理接口)
@Repository @Mapper public interface UserMapper { /** * 獲取用戶信息和身份證信息 * 一對一關聯查詢 */ @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); /** * 根據用戶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.實現實體類和數據表的映射關系
在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.編寫執行方法,獲取用戶信息和身份證信息(一對一關聯查詢)
@SpringBootTest(classes = Hl07MybatisApplication.class) @RunWith(SpringRunner.class) public class Hl07MybatisApplicationTests { @Autowired private UserMapper userMapper; /** * 獲取用戶信息和身份證信息 * 一對一關聯查詢 * @author pan_junbiao */ @Test public void getUserAndIdcardInfo() { //執行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()); } } } }
執行結果:
三、使用@Many註解實現一對多關聯查詢
需求:獲取用戶信息,同時獲取一對多關聯的權限列表
1.在MySQL數據庫創建權限信息表(tb_role)
-- 判斷數據表是否存在,存在則刪除 DROP TABLE IF EXISTS tb_role; -- 創建“權限信息”數據表 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,'系統管理員'),(1,'新聞管理員'),(1,'廣告管理員');
2.創建權限信息持久化類(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動態代理接口(UserMapper.java)
/** * 獲取用戶信息和權限列表 * 一對多關聯查詢 * @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); /** * 根據用戶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.編寫執行方法,獲取用戶信息和權限列表(一對多關聯查詢)
/** * 獲取用戶信息和權限列表 * 一對多關聯查詢 * @author pan_junbiao */ @Test public void getUserAndRolesInfo() { //執行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()); } } } }
執行結果:
四、FetchType.LAZY 和 FetchType.EAGER的區別
FetchType.LAZY:懶加載,加載一個實體時,定義懶加載的屬性不會馬上從數據庫中加載。
FetchType.EAGER:急加載,加載一個實體時,定義急加載的屬性會立即從數據庫中加載。
到此這篇關於Mybatis使用@one和@Many實現一對一及一對多關聯查詢的文章就介紹到這瞭,更多相關Mybatis 一對一及一對多關聯查詢內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- 解決mybatis竟然報Invalid value for getInt()的問題
- Mybatis結果集映射與生命周期詳細介紹
- MyBatis延遲加載策略深入探究
- Mybatis中resultMap的Colum和property屬性詳解
- springboot整合mybatis實現多表查詢的實戰記錄