一、準(zhǔ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)信息
將默認(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),未指定時將自動查找 map-underscore-to-camel-case: true #開啟自動駝峰命名規(guī)則(camel case)映射 lazy-loading-enabled: true #開啟延時加載開關(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)查詢
需求:獲取用戶信息,同時獲取一對多關(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.實(shí)現(xiàn)實(shí)體類和數(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注解實(shí)現(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í)體時,定義懶加載的屬性不會馬上從數(shù)據(jù)庫中加載。
FetchType.EAGER:急加載,加載一個實(shí)體時,定義急加載的屬性會立即從數(shù)據(jù)庫中加載。
到此這篇關(guān)于Mybatis使用@one和@Many實(shí)現(xiàn)一對一及一對多關(guān)聯(lián)查詢的文章就介紹到這了,更多相關(guān)Mybatis 一對一及一對多關(guān)聯(lián)查詢內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/weixin_43296313/article/details/120366372