zhiyuan0 2019-12-17
● 数据库表的关联查询:一对一,一对多,多对多
① 一对一:是通过在任意一方的主键,引入对方主键作为外键来实现的,就是说主键与外键为同一字段 ② 一对多:是通过在“多”的一方,添加“一”的一方的主键作为外键 ③ 多对多:是通过一张中间关系表,引入两张表的主键作为外键,两个主键成为联合主键或使用新的字段作为主键
● 在java类中关联查询:一对一,一对多,多对多
① 一对一:在本类中定义对方类型的对象,如:A类中定义B类类型的属性b,B类中定义A类类型的属性a ② 一对多:一个A类类型对应多个B类类型的情况,需要在A类中以集合的方式引入B类类型的对象,在B类中定义A类类型的属性a ③ 多对多:在A类中定义B类类型的集合,在B类中定义A类类型的集合

♦ 三种关联关系都有两种关联查询的方式,嵌套查询,嵌套结果
Tips Mybatis的yanc延迟加载配置 - 在全局配置文件中加入下面代码:
在映射文件中,<association>元素和<collection>元素中都已默认配置了延迟加载属性,即默认属性fetchType="lazy"(属性fetchType="eager"表示立即加载),所以在配置文件中开启延迟加载后,无需在映射文件中再做配置。
<settings>
<setting name="lazyLoadingEnabled" value="true" />
<setting name="aggressiveLazyLoading" value="false"/>
</settings>association - 针对pojo对象属性的映射

package com.sikiedu.beans;
public class Role {
private Integer id;
private String name;
private Integer level;
private String roletype;
private User user;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public String getRoletype() {
return roletype;
}
public void setRoletype(String roletype) {
this.roletype = roletype;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}Role.java
(1) 嵌套结果: 使用嵌套结果映射来处理重复的联合结果的子集
- property:pojo的属性名
- javaType:pojo类名
<resultMap type="Role" id="roleResultMap">
<id property="id" column="idrole" />
<result property="name" column="name" />
<result property="level" column="level" />
<result property="roletype" column="roletype" />
<association property="user" javaType="User">
<id property="id" column="id" />
<result property="username" column="username" />
</association>
</resultMap>
<select id="selectAllRoleVo" resultMap="roleResultMap">
SELECT
r.idrole,
r.name,
r.level,
r.roletype,
u.id,
u.username
FROM role r
LEFT JOIN user u
ON r.idrole = u.id
</select>(2) 嵌套查询:通过执行另外一个SQL映射语句来返回预期的复杂类型
- column:引入执行另外定制sql方法的参数值(外键)
- select:执行定制sql方法名
<resultMap type="Role" id="roleResultMap">
<id property="id" column="idrole" />
<result property="name" column="name" />
<result property="level" column="level" />
<result property="roletype" column="roletype" />
<association property="user" javaType="User" column="userid" select="com.sikiedu.mapper.UserMapper.selectUserById"/>
</resultMap>
<select id="selectRoleById" resultMap="roleResultMap">
SELECT * FROM role WHERE idrole = 1
</select><resultMap>元素中,包含了一个<collection>子元素,MyBatis就是通过该元素来处理一对多关联关系的
<collection>子元素的属性大部分与<association>元素相同,但其还包含一个特殊属性 - ofType
ofType属性与javaType属性对应,它用于指定实体对象中集合类属性所包含的元素类型。
<collection >元素的使用也非常简单,同样可以参考如下两种示例进行配置,具体代码如下:
多对多的关联关系查询,同样可以使用前面介绍的<collection >元素进行处理(其用法和一对多关联关系查询语句用法基本相同)
嵌套查询与嵌套结构优缺点:
嵌套查询:查询语句写起来简单,但是执行的sql语句多,性能要低一。 嵌套结果:查询语句写起来难一点,而且sql语句只执行一条,性能相对较高。
部分转载至 - @六月·飞雪