MySQL EntityManager范围查询

时间:2014-01-23 11:03:22

标签: java mysql hibernate hibernate-entitymanager

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

    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 Object的列表:

List{Q1Statistic, Q2Statistic, Q3Statistic, Q4Statistic}

1 个答案:

答案 0 :(得分:1)

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

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

<强> 修改

问题就像问题在你的查询中尝试以下查询希望这对你有所帮助

<强> QUERY

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)