Search code examples
javahibernatehibernate-onetomany

Hibernate OneToMany List or Iterator different?


@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()) {
    ...
}

I read the answer from here: difference between query.list and query.iterate

Obviously there is difference between list() and iterator() (in Query). What if I use it in the OneToMany list? like the example above, is there difference in term of performance? memory?


Solution

  • I read up this Hibernate chapter which explain the proxy performance in detail.

    The entity's mapping FetchType by default is lazy, which, hibernate will create a proxy around the attribute.

    Upon calling list.size() (and etc), hibernate will start to load all the children objects.

    If we don't want to load all, we can use the new feature called extra lazy. It will issue select statement for specific record only, for example, list.get(3) select fourth row only.

    If we annotate the attribute with eager, then hibernate will load all the children objects (use outer join, which will have duplicate issue) upon it load the parent object. In this case, there is no proxy wrapping around the attribute. It will not have performance difference, not matter we use it as a list or iterator.