Group by date / time

#1

Hi,

I'm trying to create reporting query that will return entities grouped by year / mont / day. Each entity has it's own field that holds java.lang.Date. There is no function like YEAR(), MONTH() or DAY() in ODB. So, how to build queries similar to something like this:

SELECT COUNT(id) 
FROM stats 
WHERE YEAR(record_date) = 2009 
GROUP BY YEAR(record_date), MONTH(record_date)

or maybe something like this:

SELECT COUNT(id) 
FROM stats 
WHERE YEAR(record_date) = 2009 
GROUP BY DATE_FORMAT(record_date, '%Y%m')

?

#2

Following your question, and since some JPA implementations support these expressions (as an extension to JPA) - support of date/time methods (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND) was just added to ObjectDB in build 2.2.8_02.

For example, the following test:

import java.util.*;
import java.sql.*;

import javax.persistence.*;


public final class T383 {

    public static void main(String[] args) {
        EntityManagerFactory emf =
            Persistence.createEntityManagerFactory("$objectdb/db/test.odb");
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();
        MyEntity e1 = new MyEntity();
        Calendar c = Calendar.getInstance();
        c.set(2099, 11, 31, 23, 59, 58);
        e1.t = new Timestamp(c.getTime().getTime());
        em.persist(e1);
        em.getTransaction().commit();

        Query query = em.createQuery(
            "SELECT YEAR(e.t), MONTH(e.t), DAY(e.t), " +
            "HOUR(e.t), MINUTE(e.t), SECOND(e.t) FROM MyEntity e",
            Tuple.class);
        List resultList = query.getResultList();
        System.out.println(resultList);

        em.close();
        emf.close();
    }
   
    @Entity
    public static final class MyEntity {
        private Timestamp t;
    }  
}

should produce this output:

[[2099, 12, 31, 11, 59, 58]]
ObjectDB Support
#3

Thanks a lot! Everything works as expected :)

Reply