Hibernate Select Top and Bottom n Rows with Criteria

前端 未结 7 1966
孤街浪徒
孤街浪徒 2021-02-07 00:33

Let\'s say I have two tables, Books and Reviews. Reviews has a column, stars, that can have a value between 1 and 5. A Book can have many Reviews.

How would I select al

7条回答
  •  滥情空心
    2021-02-07 01:01

    This would typically be done with something like a union, which you can't do in HQL.

    You can do this, though, in HQL

    WHERE id in ([SELECT top 3]) or id in ([SELECT bottom 3])
    

    I don't have a way to test this, but this might work too.

    DetachedCriteria topN = [ your criteria ] 
    DetachedCriteria bottomN = [ your criteria ] 
    
    session.createCriteria(..._
        .add( Property.or(Property.forName("id").in(topN),Property.forName("id").in(bottomN) )
        .list();
    

提交回复
热议问题