Raf*_*ruz 3 java string hibernate
我正在使用Hibernate Query by Example(QbE)和一个具有很多String属性的pojo,以及另一个属性,如Boolean,Date等.
问题是我正在为该实体创建一个搜索页面,用户可以在其中为所有字段设置过滤器值,但如果用户将任何String字段留空,则Hibernate会将此属性包含在查询中,从而破坏结果.
我知道我可以按属性检查属性以查看它是否为空并排除属性或设置为null.但这似乎是一个丑陋的决议.
我想知道是否可以通用方式检查所有这些字符串属性,如果为空则将它们设置为null.我怎么能以美丽的方式做到这一点?
提前致谢!
如果您直接使用Hibernate:
ReflectionUtils.nullifyStrings( o );
Example example = Example.create(yourObject)
.excludeZeroes()
.enableLike()
.list();
Run Code Online (Sandbox Code Playgroud)
编辑
您可以使用以下代码轻松地使所有空字符串字段无效:
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,excludeZeroes将按预期工作.
| 归档时间: |
|
| 查看次数: |
5080 次 |
| 最近记录: |