从零开始 Spring Boot 67:JPA 中的惰性元素
惰性加载带来的问题
在实体类之间建立关系时,可以选择“惰性加载”,比如:
@Entity
public class Student {
// ...
@OneToMany(mappedBy = "student",
cascade = CascadeType.ALL,
fetch = FetchType.LAZY)
@Builder.Default
private List<Email> emails = new ArrayList<>();
// ...
}
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {
"account", "domain"}))
public class Email {
// ...
@Setter
@ManyToOne
@JoinColumn(name = "student_id")
private Student student;
}
@OneToMany
的fetch
属性可以选择FetchType.LAZY
或FetchType.EAGER
,前者是惰性加载,后者是急切加