我有一张表来记录登录活动。在我的应用仪表板中,我想在图表中显示最后一次登录。每小时间隔记录的用户数。查询将返回如下结果:
time count
------- --------
9.00.00 - 9.59.59 1
10.00.00 - 10.59.59 0
11.00.00 - 11.59.59 13
12.00.00 - 12.59.59 7
13.00.00 - 13.59.59 4
实体(LoginActivity)
有dateLastUpdated
字段,查询应在该字段上运行。获得预期结果的查询是什么?还将欣赏正确的本机解决方法查询。
答案 0 :(得分:6)
试试这个
Query query = session.createQuery("select la from LoginActivity la where la.dateLastUpdated > :date");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -12);
Date date = cal.getTime();
query.setParameter("date", date);
List result = query.list();
这是一个较短的例子
Query query = session.createQuery("select la from LoginActivity la where la.dateLastUpdated > :date");
query.setParameter("date", new Date(System.currentTimeMillis() - 12*60*60*1000);
List result = query.list();
修改强>
遵循Guillaume Polet的示例(upvoted),事实证明有一种JPA方法可以做到这一点(比使用数据库供应商特定的SQL函数要好得多)。这段代码对我有用
String query = "select hour(la.dateLastUpdated) as hour, count (la) from LoginActivity la " +
"where la.dateLastUpdated > :date " +
"group by hour(la.dateLastUpdated) " +
"order by hour(la.dateLastUpdated)";
List<Object[]> objects = getSession().createQuery(query).setParameter("date", date).list();
for (Object[] o : objects) {
Object hour = o[0];
Object count = o[1];
System.out.println(hour + ".00.00 - " + hour + ".59.59\t" + count);
}
答案 1 :(得分:2)
您的查询需要依赖一些hibernate细节来处理分组和时间间隔操作。
Coul没有测试它,但它应该是那些行
String query = "Select day (la.dateLastUpdated) as day, hour(la.dateLastUpdated) as hour, count (la)
From LoginActivity la
Where la.dateLastUpdated > :date
Group by day, hour
Order by day, hour";
List <Object []> objects = em.createQuery (query, Object [].class).setParameter ("date", new Date (System.currentTimeInMillis ()-TimeUnit.HOURS.toMillis (12))).getResultList ();
for(Object [] o:objects) {
Object hour = o[1];
Object count = o [2];
System.out.println (hour + ".00.00 - " + hour + "59.59\t" + count);
}