该方法必须返回类型为Specification< Employee>的结果.在Java 8中 [英] This method must return a result of type Specification<Employee> in Java 8
本文介绍了该方法必须返回类型为Specification< Employee>的结果.在Java 8中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Lambda表达式返回返回值?
How to return using if else using Lambda expression ?
public static Specification<Employee> textInAllColumns(Object value) {
if (value instanceof String) {
return (root, query, builder) -> builder
.or(root.getModel().getDeclaredSingularAttributes().stream()
.filter(a -> {
return a.getJavaType()
.getSimpleName()
.equalsIgnoreCase("String") ? true : false;
})
.map(a -> builder.like(root.get(a.getName()), getString((String) value)))
.toArray(Predicate[]::new));
} else if (value instanceof Integer) {
return (root, query, builder) -> builder
.or(root.getModel().getDeclaredSingularAttributes().stream()
.filter(a -> {
return a.getJavaType()
.getSimpleName()
.equalsIgnoreCase("Integer") ? true : false;
})
.map(a -> builder.equal(root.get(a.getName()), value))
.toArray(Predicate[]::new));
}
}
我遇到以下错误:
此方法必须返回规范类型的结果
This method must return a result of type Specification
@GetMapping("/findEmployees")
public ResponseEntity<List<Employee>> findEmployees(@RequestParam Object searchValue) {
List<Employee> employees = employeeService.searchGlobally(searchValue);
return new ResponseEntity<>(employees, HttpStatus.OK);
}
推荐答案
您可以执行以下操作;
You can do something like this;
public static Specification<Employee> textInAllColumns(Object value) {
return (root, query, builder) -> builder.or(root.getModel().getDeclaredSingularAttributes().stream()
.filter(attr -> attr.getJavaType().equals(value.getClass()))
.map(attr -> map(value, root, builder, attr))
.toArray(Predicate[]::new));
}
private static Object map(Object value, Root root, CriteriaBuilder builder, SingularAttribute a) {
switch (value.getClass().getSimpleName()) {
case "String":
return builder.like(root.get(a.getName()), getString((String) value));
case "Integer":
return builder.equal(root.get(a.getName()), value);
case "Date":
return //date mapping
default:
return //default;
}
}
在map()
方法中隐藏if
逻辑...
hiding the if
logic in the map()
method...
将端点更新为;
findEmployees(@RequestParam String searchValue) { }
因为所有输入都可以接受为String
类型;
Since all input can be accepted as type String
;
Object finalValue = searchValue;
try {
finalValue = Integer.parseInt(searchValue);
} catch (Exception e) {
// ignore
}
try {
finalValue = parseDateFromStr(searchValue);
} catch (Exception e) {
// ignore
}
// use finalValue as input to your logic, it will contain correct type
这篇关于该方法必须返回类型为Specification< Employee>的结果.在Java 8中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文