I'm using Hibernate Query by Example (QbE) with a pojo that has a lot of String properties, and also other properties like Boolean, Date, etc....
The problem is that I'm creating a search page for that entity where the user can set filters values for all fields. But if the user leaves any String field empty, Hibernate include this property into query, breaking the results.
I know that I can check property by property to see if it is empty and exclude the property or set it as null. But this seems an ugly resolution.
I wish to know if it is possible to check in a generic way all those String properties, and set them as null if empty. How I can do this in a more elegant manner?
If you are using Hibernate directly:
ReflectionUtils.nullifyStrings( o );
Example example = Example.create(yourObject)
.excludeZeroes()
.enableLike()
.list();
EDIT
You can easily nullify all your empty String fields with the following code:
public class ReflectionUtils {
public static void nullifyStrings( Object o ) {
for ( Field f : o.getClass().getDeclaredFields() ) {
f.setAccessible(true);
try {
if ( f.getType().equals( String.class ) ) {
String value = (String) f.get( o );
if ( value != null && value.trim().isEmpty() ) {
f.set( o , null);
}
}
} catch ( Exception e ) {
throw new RuntimeException(e);
}
}
}
}
And now the excludeZeroes is going to work as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With