【问题标题】:Using GROUP BY with OpenJPA将 GROUP BY 与 OpenJPA 一起使用
【发布时间】:2014-07-24 16:50:35
【问题描述】:

我正在使用 OpenJPA 将我的数据库中的 cmets 加载到评论对象中。评论对象还具有类别、来源(字符串)和评论时间字段。这与 OpenJPA 配合得很好,我喜欢 Comment 表中的 Comment 对象,一切都很好。

对于摘要视图,我有兴趣对类别和来源进行 GROUP BY 查询,以便对于每个来源,我可以查看有多少可用 cmets 的细分。

SELECT source, category, count(category) FROM Comments GROUP BY source,category

现在,我的想法是使用实​​体管理器创建此查询,并让它以某种方式使用 CommentSummary 对象而不是 Comment 对象。我不知道如何告诉 OpenJPA 如何做到这一点。似乎所有使用 GROUP BY 的示例都没有考虑获取基础对象本身。

我尝试创建一个名为“CommentSummary”的视图,但 OpenJPA 想要修改表以添加一个 id 字段 - 也许如果我简单地告诉它源和类别字段是主键,它会起作用。我只是有点困惑,在我能理解映射到我的问题的任何地方都没有直接解决这个问题。

有没有人成功做到这一点?我应该做些什么不同的事情?

【问题讨论】:

    标签: java sql jpa group-by openjpa


    【解决方案1】:

    假设你有一个带有构造函数的对象 CommentSummary,它接受参数 source、category 和 count,你可以尝试:

    SELECT NEW x.y.z.CommentSummary(c.source, c.category, count(c.category)) FROM Comments c GROUP BY c.source, c.category
    

    CommentSummary 对象:

    package x.y.z;
    
    public class CommentSummary {
      private String source;
      private String category;
      private int categoryCount;
    
      // attribute getters/setters
    
      public CommentSummary(String source, String category, int count) {
        this.source = source;
        this.category = category;
        this.count = count;
      }
    }
    

    【讨论】:

    • 我得到一个异常:“cmetsummary”不是表、复合类型或外部表 {stmnt 6561998 ALTER TABLE CommentSummary ADD id BIGINT} [code=0, state=42809]
    • CommentSummary 不是 JPA 实体,它是一个普通的 POJO。
    • 哦,我明白了!我现在正在追逐异常......指定的持久类“CommentSummary”无法在急切初始化模式下加载。谢谢你的帮助,但我还没到那里。
    猜你喜欢
    • 2017-10-11
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 2022-10-22
    相关资源
    最近更新 更多