0
我創建了一個查詢,它假設返回一些計數行。我使用mysql查詢瀏覽器測試了我的查詢,它工作得很好(它返回正確的結果)。然而,當我用addScalar方法在hibernate中使用相同的查詢時,它返回了一個很大的隨機數。例如,第一次可能會返回5390,第二次可能會返回9380,第三次可能會出現不同的結果1。Sql count在Hibernate中返回一個奇怪的值
這是否意味着hibernate不支持sql計數功能?或者我做錯了什麼?
下面是一些相關的代碼:
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);
}
}
在您使用它的地方發佈您的查詢和代碼 – soulcheck
請發佈您的代碼以供審查 –