Is there a good reason that getSession() is not a public method (like getQueryString). I know data hiding/encapsulation is of importance and should be enforced where possible!
The query string has a public getQueryString and I was just wondering if mistakenly the public/protected modifier for getSession was forgotten?
I'm writing adapters for various data sources for a datagrid JSP component. The data sources may be simple collections, lists etc. I also support hibernate queries. For supporting paging I have defined an interface to request an iterator (for the elements of a page) and the size of the collection(for computing the number of pages).
For a hibernate query I need to to modify the original query string such that I can retrieve just a "count(*) for some query. With this modified query I have to create a new query instance and therefore I need access to the session field.
I can't get the session from anywhere else since I can't make assumptions who has created the passed query instance.
Meanwhile I have helped by using reflection but with some SecurityManager that might fail!
Code:
public QueryDataSourceImpl(Query query) {
super();
this.query = query;
}
public Iterator iterator(int fromIndex, int toIndex) throws DataSourceException {
query.setFirstResult(fromIndex);
query.setMaxResults(toIndex - fromIndex);
try {
return query.list().iterator();
} catch (HibernateException e) {
throw new DataSourceException(e);
}
}
public int size() throws DataSourceException {
String queryString = query.getQueryString();
int fromPosition = queryString.toLowerCase().indexOf("from ");
if (fromPosition >= 0) {
queryString = "select count(*) " + queryString.substring(fromPosition);
}
Method getSessionMethod;
try {
getSessionMethod = query.getClass().getSuperclass().getDeclaredMethod("getSession", new Class[] {
});
getSessionMethod.setAccessible(true);
Session session = (Session) getSessionMethod.invoke(query, new Object[] {
});
Query sizeQuery = session.createQuery(queryString);
return sizeQuery.list().size();
} catch (SecurityException e1) {
} catch (NoSuchMethodException e1) {
} catch (HibernateException e) {
throw new DataSourceException(e);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
try {
return query.list().size();
} catch (HibernateException e) {
throw new DataSourceException(e);
}
}