我创建了一个查询,假设返回一些计数行。我使用mysql查询浏览器测试了我的查询,它工作得很好(它返回正确的结果)。但是,当我使用addScalar方法在hibernate中使用相同的查询时,它返回了一个非常大的随机数。例如,第一次可以返回5390,第二次可以返回9380,第三次可以是预期结果的第三次1。
这是否意味着hibernate不支持sql count函数?或者我做错了什么?
以下是一些相关代码:
String totalStr = ", count(e.event_date) as total ";
//its a complex query but please pay attention to "count"
final String sql = "select s.section_id, s.title as section_title, m.module_id, m.title as module_title, e.event_date as read_section_date, e.read_user_id, c.course_id as site_id " + totalStr +
"from melete_course_module c, melete_module m, melete_section s, sakai_event se, " +
"(select e.event, date_format(e.event_date, '%Y/%m/%d') as event_date ,(substring(e.ref, locate('/', e.ref)+1)) as read_section_id, (substring(e.ref, 1, locate('/', e.ref)-1)) as read_user_id from sakai_event e) e " +
"where c.course_id = :siteId and c.module_id = m.module_id and m.module_id = s.module_id and e.event = 'melete.section.read' and s.section_id = read_section_id group by read_section_date";
//retrieve data from the query.
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.createSQLQuery(sql)
//.addScalar("id", Hibernate.LONG)
.addScalar("site_id", Hibernate.STRING)
.addScalar("section_id", Hibernate.LONG)
.addScalar("section_title", Hibernate.STRING)
.addScalar("module_id", Hibernate.LONG)
.addScalar("module_title", Hibernate.STRING)
.addScalar("read_section_date", Hibernate.DATE)
.addScalar("read_user_id", Hibernate.STRING)
.addScalar("total", Hibernate.LONG);
if(siteId != null) {
q.setString("siteId", siteId);
}
List<Object[]> records = q.list();
List<SectionVisits> results = new ArrayList<SectionVisits>();
if(records.size() > 0){
int index = 0;
for(Iterator<Object[]> iter = records.iterator(); iter.hasNext();) {
Object[] s = iter.next();
SectionVisits c = new SectionVisitsImpl();
c.setId(index);
c.setSiteId((String)s[0]);
c.setSectionId(Long.valueOf(s[1].toString()));
c.setSectionTitle((String)s[2]);
c.setModuleId(Long.valueOf(s[3].toString()));
c.setModuleTitle((String)s[4]);
c.setDate((Date)s[5]);
c.setUserId((String)s[6]);
c.setCount(Long.valueOf(s[7].toString()));
results.add(c);
index++;
}
}
return results;
}
};
return (List<Stat>) getHibernateTemplate().execute(hcb);
}
}
答案 0 :(得分:0)
Hibernate不支持clouse中的子选择。当我发现这个jira问题时,我尝试了很多东西而放弃了。
见https://hibernate.onjira.com/browse/HHH-3356
但是如果你必须使用subselect,你可以创建数据库视图并在sql中将它们用作普通表。