I have three classes which are country,state and suburb. Each country has many states and each state has many suburbs.
My hibernate is 4.2.1.Final.
The problem is that although FetchType of states is defined EAGER, I cant retrieve suburbs of each state.
I read this answer as well. As I do not want to retrieve all the states ad suburbs any time I am retrieving the countries. So I suppose need to override the fetching strategy using criteria rather than using
@LazyCollection(LazyCollectionOption.FALSE)
Country
@Entity
public class Country {
private List<States> states;
...
public Country(){
this.states = new ArrayList();
}
@OneToMany (cascade = CascadeType.ALL)
public List<States> getStates() {
return states;
}
....
}
States
@Entity
public class States {
private long id;
private String name;
private List<Suburbs> suburbs;
...
public States(){
this.suburbs = new ArrayList();
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<Suburbs> getSuburbs() {
return suburbs;
}
}
Suburbs
@Entity
public class Suburbs {
private long id;
private String name;
....
}
Code
Criteria criteria = session.createCriteria(Country.class, "country")
.createAlias("country.states", "states");
ProjectionList pl = Projections.projectionList();
pl.add(Projections.property("states.id").as("id"));
pl.add(Projections.property("states.name").as("name"));
criteria.setProjection(pl);
criteria.setResultTransformer(new
AliasToBeanResultTransformer(States.class));
criteria.add(Restrictions.eq("country.id", id));
List<States> statesList = new ArrayList();
statesList = (List<States>) criteria.list();
System.out.println(">>>"
+ statesList.get(0).getSuburbs().size());
>>>>> returns Zero