I have successfully built an hibernate criteria query. A common use case, it to perform the search ( .list() ) but also get the count of maximal number of hits.
Now, this is not an issue if you build the criteria twice. But that seems overly redundant. What if I wanted to do more than count? Do I have to rebuild the criteria again and again ?
I have seen tricks like:
Code:
c.setResultTransformer( Criteria.ROOT_ENTITY )
c.setProjection( null )
but this is not it. This is only valid for projections, and to me it appears to be buggy ( using aliases makes it go bananas )
Basically, I want to get another copy of my criteria, and move in two, three ... separate directions. Why isn't there a clone? How can I implement a clone?
I found and altered this:
Code:
public Criteria copy(Criteria criteria) {
try {
ByteArrayOutputStream baostream = new ByteArrayOutputStream();
ObjectOutputStream oostream = new ObjectOutputStream(baostream);
oostream.writeObject(criteria);
oostream.flush();
oostream.close();
ByteArrayInputStream baistream = new ByteArrayInputStream(baostream.toByteArray());
ObjectInputStream oistream = new ObjectInputStream(baistream);
Criteria copy = (Criteria) oistream.readObject();
oistream.close();
return copy;
}
catch (Throwable t) {
throw new HibernateException(t);
}
}
Which actually returns a hibernate criteria, but as soon as you call .list() there is an exception. Probably not correctly used.
( The original was using DetachedCriteria, plus serialization seems to be a requirement.
https://forum.hibernate.org/viewtopic.php?p=2266068 )
I am guessing I need to make a new Object that extends Criteria, and implements Serializable to make the above work?
Serialized objects are however supposed to be slow though, am I better off just rebuilding my Criteria again and again then?
There is this class also:
https://www.hibernate.org/hib_docs/v3/api/org/hibernate/util/SerializationHelper.htmlnot sure how to use it though.
Please just write on top of your mind. Let's crack this one :)
Sincerely / Moe