How can I fetch a many to one relationship in a JSP page? I tried
<s:property value="group.division.name" />
but no data appeared on the JSP.
The Group
can belong to one Division
.
public class Group implements java.io.Serializable {
..
private Division division;
..
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "div_id", nullable = false)
public Division getDivision() {
return this.division;
}
public void setDivision(Division division) {
this.division = division;
}
}
And
public class Division implements java.io.Serializable {
...
private String name;
private Set<Group> groups = new HashSet<Group>(0);
@Column(name = "name", nullable = false, length = 50)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "division")
public Set<Group> getGroups() {
return this.groups;
}
public void setGroups(Set<Group> groups) {
this.groups = groups;
}
}
I think, it's because of your FetchType.LAZY
. Remove that part, it'll fetch it eagerly by default, if I'm not mistaken -- didn't touch Hibernate for a long time, since it's @ManyToOne
.
EAGER
will try to use an outer join to retrieve the associated object, while LAZY
will only trigger an explicit SELECT
statement when the associated object is accessed for the first time. Now, here is caveat, the LAZY
thing will only work, and fire an explicit SELECT
to load the related entities, within the transaction. In your case, the transaction is already ended, it seems; therefore it's not able to retrieve the related entity.
You might like to read this question here, it discussed this thing briefly, in the question and one of the answer.