hibernate - what happens when father.getS sounds () is called when the collection is lazy

advertisements

assume i got

 class Father{

private Integer fatherId;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="FATHERID", nullable=false)
public Integer getFatherId() {
    return fatherId;
}    

Set<Son> sons;

@OneToMany(fetch=FetchType.LAZY)
@JoinColumn(name="FATHERID")
public Set<Son> getSons() {
    return airlineFlights;
}
}

and Son

   class Son{

Integer sonId
@Id
@GeneratedValue(generator="identity")
@GenericGenerator(name="identity", strategy="identity")
@Column(name="SONID", nullable=false)
public Integer getSonId() {
    return sonId;
}

 Father father;

     @ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="FATHERID", nullable=false)
public Father getFather() {
    return father;
}

}

now lets assume i got this code :

 Father f = session.load(Father.class, 1);
 f.getSons();

f is a simple POJO and the collection of sons is lazy , so what will happen here ? how is gonig to the database and query for those sons , we are in simple JVM where simple get is called , how does hibernate work there?

EDIT: what happens when getSons(), is called can you give the full cycale ?


It works the same was as it would in any environment. Hibernate will make a call to the database to retrieve the lazy-loaded collection, assuming an active session exists. Note that if you have a different session active from the one used to load the parent object, that you will need to merge the parent first.

As to how it works - byte code instrumentation. Behind the scenes Hibernate creates a 'proxy' object to wrap your entity, and makes method calls from this proxy as needed to fulfill the caller requests.

Very roughly, something like this happens:

Father (FatherProxy) -> Lazy Collection Reference -> Session -> Load Entities