version : 3.2.6ga
DB: Mysql 5.1
Java beginner
Hi all, first of all I would like to ask quite general question.
What do you think about having a method like 'countNamedQueryResults' in DAO class.
The method will consume namedQuery name and a HashMap of properties for initialization of named parameters (key ->namedparametername, value-> value to be used for that parameter).
The method will transform namedquery and return only number od records which would be returned by that query with given parameters.
The purpose of this is to stop writing separate counting queries corresponding to results's getters queries.
I know I could use list().size() but that would force hibernate to select all objects and then count them (correct me if I am wrong).
Here is my initial proposition, with many bugs ect. but should work for named queries formatted like :
SELECT Entity FROM entities and joins and whatever else s WHERE parametrisedconditions1 = :val1 and parametrisedconditions2 = :val2 ...
What do you think about this ?
Code:
public Number count(String namedquery, HashMap paramsmap ){
Session session = null;
Transaction tx = null;
Object identity = null;
Number cnt = null;
try {
identity = createSession();
session = currentSession();
tx = session.beginTransaction();
String queryString = session.getNamedQuery(namedquery).getQueryString();
// add count statement to given namged query
// to do: check this reg expression if fair enought
queryString = queryString.replaceAll("SELECT\\s+(\\w+)\\s+FROM", "SELECT COUNT($1.id) FROM ");
Query q = session.createQuery(queryString) ;
String namedParams [] = session.getNamedQuery(namedquery) .getNamedParameters();
//q.setProperties(paramsmap) ;
for (String namedparam : namedParams){
q.setParameter(namedparam, paramsmap.get(namedparam) ,Hibernate.INTEGER ) ;
}
cnt = (Number) q.uniqueResult();
tx.commit();
tx=null;
return cnt ;
} catch (Exception e) {
log.error(e);
tx.rollback();
} finally {
closeSession(identity);
}
return null ;
}
example named query:
Code:
@NamedQuery(name = "StrukturyCment.getChildsByParentId", query = "SELECT s FROM structs s WHERE s.deleted = 0 and s.parent=:parent"),
btw: hibernate bug?
when I use query.setProperties(paramsmap) hibernate requires different types for named parameters than fx. query.setInteger('param',val), example:
I can easly do something like that:
query.SetInteger('parent', new Integer(123123) );
but when I do something like this:
HashMap paramsmappng = new HashMap();
paramsmappng.put("parent", new Integer( 293398 )) ;
query.setProperties( paramsmappng ) ;
I get error like:
instance not of expected entity type: java.lang.Integer is not a: my.package.myClass
I would like to ommit Hibernate.INTEGER as well - paramsmap should be able to store different types of values
ufff - hope anyone will at last try to understand at last part of my scribbles. If you dont please ask question :)
cheers for any ...
[/code]