我正在对数据库条目进行一些过滤,最终得到了一些我不喜欢的丑陋代码。
我有我的MyFilterResolverFactory
班级,在那里我建立和归还我的MyFilterResolver
链条。
public abstract class MyFilterResolver {
protected MyFilterResolver nextResolver = EMPTY;
protected List<Predicate> predicates;
public List<Predicate> resolve(MyFilter filter, CriteriaBuilder cb, Root<MyEntity> root) {
this.predicates = new ArrayList<Predicate>();
resolveFilter(filter, cb, root);
this.predicates.addAll(this.nextResolver.resolve(filter, cb, root));
return this.predicates;
}
protected abstract void resolveFilter(MyFilter filter, CriteriaBuilder cb, Root<MyEntity> root);
public void attachNextResolver(MyFilterResolver nextResolver) {
this.nextResolver = nextResolver;
}
public static MyFilterResolver EMPTY = new MyFilterResolver() {
@Override
public List<Predicate> resolve(MyFilter filter, CriteriaBuilder cb, Root<MyEntity> root) {
return new ArrayList<Predicate>();
}
@Override
protected void resolveFilter(MyFilter filter, CriteriaBuilder cb, Root<MyEntity> root) {
}
};
}
还有一个丑陋的具体实现:
public class MyDateFilterResolver extends
MyFilterResolver {
@Override
protected void resolveFilter(MyFilter filter, CriteriaBuilder cb,
Root<MyEntity> root) {
if (filter != null) {
Date dateExact = filter.getDateExact();
Date dateAfter = filter.getDateAfter();
Date dateBefore = filter.getDateBefore();
if (dateExact != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateExact);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date dayStart = calendar.getTime();
calendar = Calendar.getInstance();
calendar.setTime(dayStart);
calendar.add(Calendar.DATE, 1);
calendar.add(Calendar.MILLISECOND, -1);
Date dayEnd = calendar.getTime();
super.predicates.add(
cb.greaterThanOrEqualTo(
root.get("date").as(Date.class),
dayStart
)
);
super.predicates.add(
cb.lessThanOrEqualTo(
root.get("date").as(Date.class),
dayEnd
)
);
}
if (dateAfter != null) {
super.predicates.add(
cb.greaterThanOrEqualTo(
root.get("date").as(Date.class),
dateAfter
)
);
}
if (dateBefore != null) {
predicates.add(
cb.lessThanOrEqualTo(
root.get("date").as(Date.class),
dateBefore
)
);
}
}
}
}
MyFilter
class 是一个普通的 POJO,只有 getter/setter。
我想摆脱这些if (something != null)
检查,但我不知道如何。