Set all empty strings properties to null

I'm using Hibernate Query by Example (QbE) with a pojo that have a lot of String properties, and also another properties like Boolean, Date, etc.

The problem is that I'm creating a search page for that entity, where the user will can set filters values for all fields, but if the user leave 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 as null. But this seems an ugly resolution.

I wish to know if is possible to check in a generically way all those Strings properties, and set they as null if is empty. How I can do this in a beautiful way?

Thanks in advanced!


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.

链接地址: http://www.djcxy.com/p/76164.html

上一篇: 仅当该值不为null时才设置属性

下一篇: 将所有空字符串属性设置为空