休眠:选择N行,但在一列中只有唯一值

时间:2012-02-01 02:47:39

标签: java hibernate

我想用Hibernate标准实现this

假设我有数据(来自链接):

ID  Name            City            Birthyear
1   Egon Spengler   New York        1957
2   Mac Taylor      New York        1955
3   Sarah Connor    Los Angeles     1959
4   Jean-Luc Picard La Barre        2305
5   Ellen Ripley    Nostromo        2092
6   James T. Kirk   Riverside       2233
7   Henry Jones     Chicago         1899

我想用Hibernate(来自链接)实现这个:

SELECT P.*, COUNT(*) AS ct
   FROM people P
   JOIN (SELECT MIN(Birthyear) AS Birthyear
              FROM people 
              GROUP by City) P2 ON P2.Birthyear = P.Birthyear
   GROUP BY P.City
   ORDER BY P.Birthyear ASC 
   LIMIT 10;

如果我有实体:

@Entity
@Table(name = "people")
public class People {
    @Id
    private int id;

    @Column
    private String name;

    @Column
    private String city;

    @Column 
    int birthyear;
}

然后我可以制作一个没有自我加入部分的标准(这可能不起作用):

Criteria criteria = sessionFactory.getCurrentSession()
   .createCriteria(People.class, "people")
   .setProjection(Projections.projectionList()
        .add(Projections.property("people.id"))
        .add(Projections.property("people.name"))
        .add(Projections.property("people.city"))
        .add(Projections.groupProperty("people.city)))
    .addOrder(Order.asc("people.birthyear"));

如何实现自联接部分?

1 个答案:

答案 0 :(得分:1)

我尝试使用HQL,但仍然有点复杂,here您可以找到详细信息。

我发现使用原生查询更容易(但可能不那么优雅)。

String hql="SELECT P.*, COUNT(*) FROM people P JOIN 
            (SELECT MIN(Birthyear) AS Birthyear FROM people GROUP by City) P2 ON P2.Birthyear = P.Birthyear
             GROUP BY P.City ORDER BY P.Birthyear ASC";

SQLQuery createSQLQuery = sessionFactory.getCurrentSession().createSQLQuery(hql);
List list = createSQLQuery.list();

就像我说的,也许这不是最优雅的解决方案,但创建和获取数据似乎仍然更快。

希望有所帮助