gpt4 book ai didi

java - MySQL EntityManager 范围查询

转载 作者:行者123 更新时间:2023-11-29 13:17:19 25 4
gpt4 key购买 nike

我如何简化此查询,使其仅运行一次。我当前的代码:

    int year = 2014;

Query q = entityManager.createQuery("SELECT SUM(s.revenue),SUM(s.mediaSpending),SUM(s.grossProfit) FROM Sale s WHERE YEAR(s.date) = :year AND QUARTER(s.date) = :quarter");
q.setParameter("year", year);

q.setParameter("quarter", 1);
Object[] q1 = (Object[]) q.getSingleResult();

q.setParameter("quarter", 2);
Object[] q2 = (Object[]) q.getSingleResult();

q.setParameter("quarter", 3);
Object[] q3 = (Object[]) q.getSingleResult();

q.setParameter("quarter", 4);
Object[] q4 = (Object[]) q.getSingleResult();

我可以以某种方式同时查询所有 4 qartal 的列表吗?像这样的事情:

Query q = entityManager.createQuery("SELECT   SUM(s.revenue),SUM(s.mediaSpending),SUM(s.grossProfit) FROM Sale s WHERE YEAR(s.date) = :year AND QUARTER(s.date) =  ???(1-4)");

List<Object[]> q1 = q.getResultList();

编辑:结果应该是 4 个对象的列表:

List{Q1Statistic, Q2Statistic, Q3Statistic, Q4Statistic}

最佳答案

是的,您可以尝试以下代码

Session session = entityManager.unwrap(Session.class);
Query query = session.createQuery("SELECT SUM(s.revenue),SUM(s.mediaSpending),SUM(s.grossProfit) FROM Sale s WHERE YEAR(s.date) = :year AND QUARTER(s.date) = :quarter");
query.setParameter("year", year);
query.setParameter("quarter", 1);
List<Object[]> result = query.list();

另请查看Hibernate SessionFactory vs. EntityManagerFactory

编辑

看起来问题出在您的查询中,请尝试以下查询,希望这对您有帮助

查询

SELECT SUM(s.revenue),SUM(s.mediaSpending),SUM(s.grossProfit) FROM Sale s 
WHERE YEAR(s.date) = :year
GROUP BY YEAR(s.date) , QUARTER(s.date)

关于java - MySQL EntityManager 范围查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21306282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com