Wednesday, December 07, 2005

Query by example with hibernate and spring

I did this to get hibernate's query by example to work from spring 

Bibliography - David Carter - http://www.jroller.com/page/ddcarter/20051013

import org.springframework.orm.hibernate3.HibernateCallback;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.HibernateException ;

public
List getCats(final Cat cat) {
if (cat == null) {
return getHibernateTemplate().find("from Cat");
} else {
// filter on properties set in the cat
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Example ex = Example.create(cat).ignoreCase()
.enableLike(MatchMode.ANYWHERE)
.excludeZeroes();
return session.createCriteria(Cat.class).add(ex).list();
}
};
return (List) getHibernateTemplate().execute(callback);
}
}

No comments: