我已经使用 toPredicate()
方法完成了一些编码,现在我想重构它,以便我也可以在 Java 7
中使用它。
我在下面发布了一些到目前为止我已经完成的示例代码。
EntitySpecification.java
public class EntitySpecification {
public static Specification<MyEntity> textInAllColumns(String text) {
if (!text.contains("%")) {
text = "%"+text+"%";
}
final String finalText = text;
return new Specification<MyEntity>() {
@Override
public Predicate toPredicate(Root<MyEntity> root, CriteriaQuery<?> cq, CriteriaBuilder builder) {
return builder.or(root.getModel().getDeclaredSingularAttributes().stream().filter(a-> {
if (a.getJavaType().getSimpleName().equalsIgnoreCase("string")) {
return true;
}
else {
return false;
}}).map(a -> builder.like(root.get(a.getName()), finalText)
).toArray(Predicate[]::new)
);
}
};
}
}
最佳答案
Java 8 附带了 lambda 表达式 (->
)。为了在 Java 7 中使用代码,您必须将它们替换为匿名类。
如果您使用像 IntelliJ 这样的 IDE,它可以为您完成这项工作。将光标移至 ->
,然后按 ALT + ENTER
。应该会出现一个弹出窗口,并且应该有一个选项用匿名类替换 lambda
。
.filter(a -> {
if (a.getJavaType().getSimpleName().equalsIgnoreCase("string")) {
return true;
} else {
return false;
}
})
至
.filter(new java.util.function.Predicate<SingularAttribute<MyEntity, ?>>() {
@Override
public boolean test(SingularAttribute<MyEntity, ?> a) {
if (a.getJavaType().getSimpleName().equalsIgnoreCase("string")) {
return true;
} else {
return false;
}
}
})
此外,您还必须从 java.util.function
包中删除正在使用的所有内容。
您可以将 .filter()
替换为 for 循环和其中的 if 语句。对于.map()
,您必须使用for循环修改先前过滤的集合。
new Specification<MyEntity>() {
@Override
public Predicate toPredicate(Root<MyEntity> root, CriteriaQuery<?> cq, CriteriaBuilder builder) {
List<SingularAttribute<MyEntity, ?>> tempAttributes = new ArrayList<>();
for (SingularAttribute<MyEntity, ?> attribute : root.getModel().getDeclaredSingularAttributes()) {
if (attribute.getJavaType().getSimpleName().equalsIgnoreCase("string")) {
tempAttributes.add(attribute);
}
}
final Predicate[] predicates = new Predicate[tempAttributes.size()];
for (int i = 0; i < tempAttributes.size(); i++) {
predicates[i] = builder.like(root.<MyEntity>get(tempAttributes.get(i).getName()), finalText);
}
return builder.or(predicates);
}
};
我自己没有尝试过,但这应该可行,或者至少为您提供了第一步。
关于java - 重构 JPA 的 toPredicate 方法以支持 Java 7 和 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56754801/