gpt4 book ai didi

java - Hibernate OneToMany List 或 Iterator 不同?

转载 作者:行者123 更新时间:2023-12-02 12:48:13 27 4
gpt4 key购买 nike

@Entity
@Table(name = "STUDENT")
public class Student {

private long studentId;
private String studentName;
private List<Phone> studentPhoneNumbers;

....

@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "STUDENT_PHONE", joinColumns = { @JoinColumn(name = "STUDENT_ID") }, inverseJoinColumns = { @JoinColumn(name = "PHONE_ID") })
public List<Phone> getStudentPhoneNumbers() {
return this.studentPhoneNumbers;
}

public void setStudentPhoneNumbers(List<Phone> studentPhoneNumbers) {
this.studentPhoneNumbers = studentPhoneNumbers;
}
}

1)

Student student = session.loadStudent(123); // pseudocode
List phoneList = student.getStudentPhoneNumbers();
for (Phone p : phoneList) {
...
}

2)

Student student = session.loadStudent(123); // pseudocode
List phoneList = student.getStudentPhoneNumbers();
Iterator itr = phoneList.iterator();
while(itr.hasNext()) {
...
}

我从这里阅读了答案:difference between query.list and query.iterate

显然,list()iterator() 之间存在差异(在 Query 中)。如果我在 OneToMany 列表中使用它会怎样?就像上面的例子,性能上有区别吗?内存?

最佳答案

与 Hibernate 无关。

当Java编译器遇到

for (Phone p : phoneList) {
....
}

它自动生成相当于

的代码
for (Iterator<Phone> itr = phoneList.iterator(); itr.hasNext();) {
Phone p = itr.next();
....
}

因此,您所展示的两个示例本质上是相同的。

关于java - Hibernate OneToMany List 或 Iterator 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44690178/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com