Hibernate Postload and null fields on referenced entities [duplicate]
I have two entities like the ones below:
@Entity
public class Project {
@Id
private id;
private String name;
...
}
@Entity
public class Person {
@Id
private id;
private String name;
@ManyToOne
private Project project;
@PostLoad
void onLoad(){
if (project.getName() == null){
//It's always null!!!
}
}
...
}
As the code says, on onLoad the field of the related entity is always null -in fact, all field of related entity are null-. I need Hibernate to fetch the field before calling onLoad.
Any idea?
Thanks.
You must set a Fetch strategy
it might be:
FetchType.LAZY
or
FetchType.EAGER
You should define also the join column with the foreign ID.
In your code:
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "project_id")
private Project project;
精彩评论