我有这样的:做好每一天的时间段查询,把它变成一个查询
public Map<Day,Integer> getUniqueLogins(long fromTime, long toTime) {
EntityManager em = emf.createEntityManager();
try {
Map<Day,Integer> resultMap = new ...;
for (Day day : daysInPeriod(fromTime, toTime)) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> q = cb.createQuery(Long.class);
// FROM UserSession
Root<UserSession> userSess = q.from(UserSession.class);
// SELECT COUNT(DISTINCT userId)
q.select(cb.countDistinct(userSess.<Long>get("userId")));
// WHERE loginTime BETWEEN ...
q.where(cb.between(userSess.<Date>get("loginTime"), day.startDate(), day.endDate()));
long result = em.createQuery(q).getSingleResult();
resultMap.put(day, (int) result);
}
return resultMap;
} finally {
em.close();
}
}
该执行的每一天,在一定时期内查询(周期中量级是一个月)。
我可以在一个查询中得到这个特定的数据吗?我使用的是Hibernate/MySQL,但我不想要任何非标准功能。
这会工作,但那个'日期'功能从哪里来?是MySQL还是标准JPA/JPQL? Criteria API中是否有等价物? – 2010-12-15 14:27:50
我不太确定,但我不认为JPQL中有任何明确的日期操作函数(除了获取当前的日期/时间)。 – 2010-12-15 14:36:51
根据文档,date()是一个MySQL函数,它返回日期或时间戳表达式的日期。 http://dev.mysql.com/doc/refman/5.5/zh-CN/date-and-time-functions.html#function_date – 2011-01-11 02:45:08