我有两个实体Student和Address。 我正在使用FetchType.LAZY。但是,当我通过spring数据findById获取学生时,它将获取与该学生关联的地址列表。
var_dump ( curl("https://www.googleapis.com/language/translate/v2",
['key'=>$key, 'q'=>array("hello","world"),
'source'=>"en", 'target'=>'ru'] ) );
公共班学生{
@Table(name = "Student")
}
@Table(名称=“地址”) 公共课程地址{
@Column(name="name")
private String name;
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "STUDENT_ID")
@SequenceGenerator(name = "STUDENT_ID", sequenceName = "STUDENT_ID_SEQ")
@Column(name="STUDENT_ID")
private Long id;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true,fetch = FetchType.LAZY)
@JoinColumn(name = "student_id")
private List<Address> address;
}
Optional可选= repository.findById(id); 学生s = optional.get();
这正在执行两个sql,一个用于学生表,另一个用于地址表,以查找学生的相关地址。
理想情况下,学生应该只有学生数据,但关联的地址除外。
正如我们提到的延迟加载,它不应触发第二个excel。
答案 0 :(得分:0)
我建议更改: 公共班学生{
@Column(name =“名称”) 私有字符串名称;
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "STUDENT_ID")
@SequenceGenerator(name = "STUDENT_ID", sequenceName = "STUDENT_ID_SEQ")
@Column(name="STUDENT_ID")
private Long id;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true,fetch = FetchType.LAZY, mappedBy="student")
private List<Address> address;
}
然后:
@Table(name = "Address") public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "ADDRESS_ID")
@SequenceGenerator(name = "ADDRESS_ID", sequenceName = "ADDRESS_ID_SEQ")
@Column(name="ADDRESS_ID")
private Long id;
private String desc;
@ManyToOne(fetch=FetchType.LAZY)
public Student student;
}
@JoinColumn让@OneToMany端负责关联,而不是最佳选择,请尝试使用@OneToMany端的“ mappedBy”属性。