一、association
Mybatis的 association是一對一的使用的, 在 resultMap 標(biāo)簽內(nèi)使用
當(dāng)一個(gè)Bean中有 一個(gè)Object屬性需要關(guān)聯(lián)查詢出來的使用就用association標(biāo)簽
如下
查詢用戶結(jié)果 需要關(guān)聯(lián)出 角色
用戶
@Data
public class User {
private Integer id;
private String name;
private Role role;
}
角色
@Data
public class Role {
private Integer id;
private Integer userId;
private String name;
private String type;
}
sql
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL COMMENT '名稱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '用戶id',
`name` varchar(255) DEFAULT NULL COMMENT '角色名稱',
`type` varchar(255) DEFAULT NULL COMMENT '角色類型',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4;
二、使用方法
1. 方法一: 嵌套結(jié)果映射
<!-- 定義resultMap -->
<resultMap id="UserResultMap" type="User">
<result column="id" property="id"/>
<result column="name" property="name"/>
<association ofType="role" property="role">
<result column="role_id" property="id"/>
<result column="role_name" property="name"/>
<result column="role_type" property="type"/>
</association>
</resultMap>
<!--查詢語句-->
<select id="selectUserById" resultMap="UserResultMap">
select u.id ,u.name,r.id AS role_id ,r.name AS role_name ,r.type AS role_type FROM user AS u INNER JOIN role AS r ON u.id = r.user_id where u.id = #{id}
</select>
2. 方法二: 嵌套select 查詢
<!-- 定義resultMap -->
<resultMap id="UserResultMap" type="User">
<result column="id" property="id"/>
<result column="name" property="name"/>
<association ofType="role" property="role" column="id" select="selectRoleByUserId"/>
</resultMap>
<!--查詢語句-->
<select id="selectUserById" resultMap="UserResultMap">
select id , name FROM user where id = #{id}
</select>
<!--查詢語句-->
<select id="selectRoleByUserId" resultMap="Role">
select id , name,type FROM role where user_id = #{userId}
</select>
- select="selectRoleByUserId" 找的是第二個(gè)sql語句,如果調(diào)用別的xml文件中方法寫全路徑就可以找到.
- column="id" 參數(shù)id 傳多個(gè)參數(shù)的話就是 {"屬性名"="參數(shù)","屬性名"="參數(shù)"} 這樣的.
三、colleciton 一對多
collection 一對多 : https://blog.csdn.net/qq825478739/article/details/127357819