Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set all empty strings properties to null

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?

like image 871
Rafael Cruz Avatar asked Dec 21 '11 12:12

Rafael Cruz


1 Answers

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.

like image 52
Maurício Linhares Avatar answered Oct 05 '22 23:10

Maurício Linhares