Question

How can i simplify this Query, to run it only once. My current code:

    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();

can i somehow query a list for all 4 qartal at once ? Something like this:

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();

EDIT: The result should be a list of 4 Object :

List{Q1Statistic, Q2Statistic, Q3Statistic, Q4Statistic}
Was it helpful?

Solution

Yes you can try following code

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();

also have a look at Hibernate SessionFactory vs. EntityManagerFactory

EDIT

It seams like the issue is in your Query try following query hope this help you

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top