Reputation: 397
i am using criteria to select list of entities that have field that refers to other tables, so I am using aliases. The problem is, that when I to try access joined field, hibernate execute another select to the database. That is really noneffective, as this is preforming one query for each result row.
Can anyone tell me why is this happening?
usage of criteria (reduced to only relevant lines)
List<Country> list = session.createCriteria(Country.class)
.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
.createAlias("locations", "location")
.list();
for (Countries cntry : list){
cntry.getLocations().size(); // here hibernate execute another query
}
Country (the important part)
@Entity
public class Country {
// other fields as uuid etc.
@OneToMany(fetch = FetchType.LAZY, mappedBy = "country")
private List<Location> locations;
// getters and setters
}
Location (the important part)
@Entity
public class Location {
// other fields as uuid etc.
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "COUNTRY_UUID")
private Country country;
// getters and setters
}
Upvotes: 0
Views: 599
Reputation: 2983
try:
List<Country> list = session.createCriteria(Country.class)
.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
.setFetchMode("locations", FetchMode.JOIN)
.createAlias("locations", "location")
.list();
This should result in a single query that fetches all Countries and Locations.
In addition to this, you should have @BatchSize on Location. @BatchSize(size=20) will cause 1 statement for every 20 relations if you don't have the fetch mode set.
Upvotes: 1