【问题标题】:Grails: Use results of Criteria + projections as a filter on the original tableGrails:使用 Criteria + projections 的结果作为原始表的过滤器
【发布时间】:2013-02-09 02:34:32
【问题描述】:

我有以下表格/模型:

class Post {
  int id;
  String comment;
  static belongsTo = [category_id:Category];
}

我希望创建一个查询,可以根据Category 过滤掉最后一个Post(最高id)。我想要List<Post> 形式的结果。

换句话说(我相信)在 SQL 中查询将如下所示:

SELECT *
FROM
  Post AS source
  JOIN (
    SELECT MAX(id) AS id, category_id 
    FROM Post
    GROUP BY category_id
  ) AS filter
  ON source.id = filter.id;

如果我理解正确,第一步是使用HibernateCriteriaBuilder

def c = Post.createCriteria();
  def results = c.list {
    projections {
      groupProperty("category_id", "myid")
      max("id", "version")
    }
  }

所以我的问题分为两部分:

  1. 我走对了吗?

  2. 如何使用结果对象获取List<Post> 数组?

    (类似:def latest = Post.FindAllByXXX(result);

【问题讨论】:

    标签: grails hibernate-criteria createcriteria


    【解决方案1】:

    是的,你在正确的轨道上。我还会将 Post 的 id 属性添加到我的预测中:

    projections {
        property('id')
    }
    

    然后使用 id 收集所有帖子以获取帖子列表,例如:

    def latestPosts = results?.collect{Post.read(it[0])}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      相关资源
      最近更新 更多