Sakila数据库的标准查询

时间:2014-09-26 06:05:28

标签: mysql hibernate hibernate-criteria

我是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;

1 个答案:

答案 0 :(得分:0)

我们假设您OneToManyuni-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();