HibernateTemplate findByExample returns no results
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(qbeUs开发者_如何转开发er);
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?
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.
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.
You could exclude zero values by calling the excludeZeroes() method which is defined in the Example class in Hibernate. Adding hibernate.show_sql property to your hibernate.cfg.xml file will help you to see which values are set to 0 in the SQL query that Hibernate creates. https://docs.jboss.org/hibernate/orm/5.4/javadocs/org/hibernate/criterion/Example.html#excludeZeroes--
Add the following to your hibernate.cfg.xml file:
<property name="hibernate.show_sql">true</property>
Run your application. It will display the SQL query that Hibernate generates. By looking at the where clause, you will see what fields are used for filtering. Netbeans screenshot
Criteria c = session.createCriteria(Parking.class);//deprecated since 5.2
Parking p = new Parking();
p.setCity("BROOKLYN");
Example ex = Example.create(p);
ex.excludeZeroes(); //exclude zero-valued properties
c.add(ex);
Hibernate Example object will exclude zero-valued properties with the excludeZeroes() method.
You may exclude certain properties by name with excludeProperty() method, or you may exclude nothing with the excludeNone() method.
精彩评论