【问题标题】:How to execute pivot queries in JPA-Hibernate?如何在 JPA-Hibernate 中执行数据透视查询?
【发布时间】:2013-04-02 13:30:59
【问题描述】:

在 MYSQL 中我有这个查询:

我的桌子

规划 ------------------ process_id (int) project_id (int) 期间(日期时间) 总小时(双) 选择 process_id,project_id, sum( if (period="2013-04-01 00:00:00",total_hour,0)) 作为四月, sum( if (period="2013-05-01 00:00:00",total_hour,0)) 可能, sum( if (period="2013-06-01 00:00:00",total_hour,0)) 为 6 月 从计划 GROUP BY process_id,project_id;

我需要转换这个子句 SQL 以便在 JPA 中使用?

【问题讨论】:

    标签: hibernate jpa pivot-table


    【解决方案1】:

    SQL 到 JPQL

    SELECT p.process_id, p.project_id,
    sum( case when p.period="2013-04-01 00:00:00" then p.total_hour else 0 end ) as april,
    sum( case when p.period="2013-05-01 00:00:00" then p.total_hour else 0 end ) as may,
    sum( case when p.period="2013-06-01 00:00:00" then p.total_hour else 0 end ) as june,
    FROM Planning p
    GROUP BY p.process_id, p.project_id;
    

    但您仍然可以使用本机查询。

    映射你的结果集:你可以手动将你的结果集映射到一个新的bean(如果你愿意,可以使用推土机),或者你可以使用一些@SqlResultSetMapping 见How to select multiple columns with the same name using JPA native query?

    【讨论】:

    • 如何将结果集添加到新对象(示例:PlanningExtractBean.class),因为源 Bean 与结果集不同。
    • 很高兴为您提供帮助,因此请不要忘记将此答案标记为正确。谢谢
    猜你喜欢
    • 2020-11-03
    • 2017-10-23
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 2023-03-28
    • 1970-01-01
    • 2020-01-29
    相关资源
    最近更新 更多