今天上午回來設(shè)計(jì)了一點(diǎn)新聞發(fā)布系統(tǒng)周邊的功能,并實(shí)現(xiàn)了對新聞進(jìn)行重新索引的功能。
但同時(shí)在列出相關(guān)新聞的時(shí)候遇到了麻煩。就是原本運(yùn)行好好的分頁查詢代碼,居然有個(gè)小蟲子跑出來,
很是令人不爽。說來也慚愧,Hibernate也用了那么長時(shí)間了。可對底層API卻很不屬性。
查了下網(wǎng)絡(luò),把自己的一知半解說出來。
bug起源。
看看代碼:
return (PageSupport) getHibernateTemplate().execute(
new HibernateCallback() ...{
public Object doInHibernate(Session session)
throws HibernateException ...{
Criteria criteria = detachedCriteria
.getExecutableCriteria(session);
logger.debug("SQL: " + Projections.rowCount());
//執(zhí)行查詢
int totalCount = ((Integer) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();

List items = criteria.setFirstResult(startIndex)
.setMaxResults(pageSize).list();
PageSupport ps = new PageSupport(items, totalCount,
pageSize, startIndex);
return ps;
}
}, true);
相信大家對上面的代碼也很熟悉了,這個(gè)代碼第一次運(yùn)行的時(shí)候沒問題。
等你去拿第2頁的時(shí)候,就提示說出現(xiàn)NullPointer。 發(fā)現(xiàn)是((Integer) criteria.setProjection(Projections.rowCount()).uniqueResult())為Null, 也就是根本就拿不到表總數(shù)。
為此我思考了好一陣子。
后來看了別人的代碼才煥然大悟。
看第2個(gè)代碼:
return (PageSupport) getHibernateTemplate().execute(
new HibernateCallback() ...{
public Object doInHibernate(Session session)
throws HibernateException ...{
Criteria criteria = detachedCriteria
.getExecutableCriteria(session);
CriteriaImpl impl = (CriteriaImpl) criteria;

//先把Projection和OrderBy條件取出來,清空兩者來執(zhí)行Count操作
Projection projection = impl.getProjection();
logger.debug("SQL: " + Projections.rowCount());
//執(zhí)行查詢
int totalCount = ((Integer) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();

//將之前的Projection和OrderBy條件重新設(shè)回去
criteria.setProjection(projection);
if (projection == null) ...{
criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
}
List items = criteria.setFirstResult(startIndex)
.setMaxResults(pageSize).list();
PageSupport ps = new PageSupport(items, totalCount,
pageSize, startIndex);
return ps;
}
}, true);
但同時(shí)在列出相關(guān)新聞的時(shí)候遇到了麻煩。就是原本運(yùn)行好好的分頁查詢代碼,居然有個(gè)小蟲子跑出來,
很是令人不爽。說來也慚愧,Hibernate也用了那么長時(shí)間了。可對底層API卻很不屬性。
查了下網(wǎng)絡(luò),把自己的一知半解說出來。
bug起源。
看看代碼:




























相信大家對上面的代碼也很熟悉了,這個(gè)代碼第一次運(yùn)行的時(shí)候沒問題。
等你去拿第2頁的時(shí)候,就提示說出現(xiàn)NullPointer。 發(fā)現(xiàn)是((Integer) criteria.setProjection(Projections.rowCount()).uniqueResult())為Null, 也就是根本就拿不到表總數(shù)。
為此我思考了好一陣子。
后來看了別人的代碼才煥然大悟。
看第2個(gè)代碼:



































