我是Hibernate和Criteria Query的新手。我想在sakila数据库上执行操作。我想要对以下SQL
查询进行Criteria查询:
select c.city, cr.country
from city c
left join country cr
on c.country_id = cr.country_id;
答案 0 :(得分:0)
我们假设您OneToMany
和uni-directional mapping
之间有Country
City
:
@Entity
public class Country {
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name = "country_id")
private Set<City> cities = new HashSet<City>();
}
然后您可以像这样创建Criteria
查询:
Criteria criteria = getSession().createCriteria(Country.class);
criteria.createAlias("cities","c",JoinType.LEFT_OUTER_JOIN);
// This line removes the duplicate results of root entity - `Country`
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List<Country> countries = criteria.list();