【问题标题】:Set all empty strings properties to null将所有空字符串属性设置为 null
【发布时间】:2012-01-25 05:52:56
【问题描述】:

我正在使用 Hibernate Query by Example (QbE) 和一个 pojo,它有很多字符串属性,还有其他属性,如布尔值、日期等......

问题是我正在为该实体创建一个搜索页面,用户可以在其中为所有字段设置过滤器值。但是如果用户将任何 String 字段留空,Hibernate 会将此属性包含到查询中,从而破坏结果。

我知道我可以逐个检查属性以查看它是否为空并排除该属性或将其设置为空。但这似乎是一个丑陋的决议。

我想知道是否可以以通用方式检查所有这些 String 属性,如果为空,则将它们设置为 null。我怎样才能以更优雅的方式做到这一点?

【问题讨论】:

    标签: java string hibernate


    【解决方案1】:

    如果您直接使用 Hibernate:

    ReflectionUtils.nullifyStrings( o );
    Example example = Example.create(yourObject)
           .excludeZeroes() 
           .enableLike()
           .list();
    

    编辑

    您可以使用以下代码轻松取消所有空字符串字段:

    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);
            }
        }
    
    }
    
    }
    

    现在 excludeZeroes 将按预期工作。

    【讨论】:

    • 感谢您的回答,我已经尝试过了,但不起作用。
    猜你喜欢
    • 2013-06-28
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 2018-02-17
    • 2011-05-19
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    相关资源
    最近更新 更多