views:

204

answers:

2

I'm trying to use Hibernate QBE (actually, Spring's HibernateTemplate.findByExample() ) to return a list of users by their username. I use a "known good" value to search on (the username "JOHN.SMITH" does exist in the database).

Unfortunately, I get no results back. Below is the unit test.

@Test
public void testQueryByExample() {

    User qbeUser = new User();
    qbeUser.setUsername("JOHN.SMITH");

    List<User> userList = userDao.queryByExample(qbeUser);
    Assert.notNull(userList);
    Assert.isTrue(userList.size() > 0, "List of returned users must not be 0");

}

The queryByExample() method is defined in a generic DAO:

@SuppressWarnings("unchecked")
public List<T> queryByExample(T obj) {
    return getHibernateTemplate().findByExample(obj);
}

Is there any sort of special configuration needed for QBE to work?

A: 

you have to pass spring configuration file otherwise how would it will get connection and pooling information.. use @ annotation to load spring file above class declaration.

taher
The Test class is annotated with @ContextConfiguration(locations = "classpath:applicationContext.xml")The class under test is being successfully injected. My other methods that don't use QBE are fine, but QBE doesn't work.
Jason
for criteria querying you can use findByCriteria method of hibernateTemplate..
taher
+1  A: 

It was pure stupidity on my part.

The classes being used as examples had some ints and booleans (primitives) in them. Since those values default to 0 and false, the queries were failing.

Jason
Yes, `findByExample()` includes all primitive attributes in its criteria, but ignores all non-primitive attributes whose value is null. The Hibernate `Example` class, however, has more flexible criteria options. See http://docs.jboss.org/hibernate/stable/core/reference/en/html/querycriteria.html#querycriteria-examples.
Derek Mahar