一、概述
1、延迟加载:
- 就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。延迟加载也称懒加载
2、好处:
- 先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快。
3、坏处:
- 因为只有当需要用到数据时,才会进行数据库查询,这样在大批量数据查询时,因为查询工作也要消耗时间,所以可能造成用户等待时间变长,造成用户体验下降。
4、MyBatis 多表查询
在多表查询时,使用了resultMap
来实现一对一,一对多,多对多关系的操作。主要是通过 association
、collection
实现一对一及一对多映射。association
、collection
具备延迟加载功能。
二、association 延迟加载、collection 延迟加载
association : 用于一对多(一个用户对应多个账号:User ——> Account)
collection :用于多对一
第一步:封装对数据库映射的实体类 User.java、Account.java
package cn.lemon.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class User implements Serializable {
private Integer id;
private Date birthday;
private String username;
private String sex;
private String address;
private List<Account> accountList = new ArrayList<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Account> getAccountList() {
return accountList;
}
public void setAccountList(List<Account> accountList) {
this.accountList = accountList;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", birthday=" + birthday +
", username='" + username + '\'' +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
package cn.lemon.domain;
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
private User user;//关联属性,记录关联关系
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id