问题描述
我正在工作 Spring Data - 多列搜索 和 Spring Data Jpa - 类型规范<T>已弃用,我想在其中搜索多个列,例如 Date
(Java 8 LocalDateTime
, Instant
, LocalDate
等,)、Integer
和 String
数据类型.
I am working Spring Data - Multi-column searches and Spring Data Jpa - The type Specifications<T> is deprecated where I wants to search for multiple columns like Date
(Java 8 LocalDateTime
, Instant
, LocalDate
etc.,), Integer
and String
data types.
但根据我的代码,只考虑了 String
字段(根据 where
子句中的日志)::
But as per my code, only String
fields are getting considered (as per logs in where
clause)::
select
employee0_.employee_id as employee1_0_,
employee0_.birth_date as birth_da2_0_,
employee0_.email_id as email_id3_0_,
employee0_.first_name as first_na4_0_,
employee0_.last_name as last_nam5_0_,
employee0_.project_association as project_6_0_,
employee0_.status as status7_0_
from
employee employee0_
where
employee0_.first_name like ?
or employee0_.email_id like ?
or employee0_.status like ?
or employee0_.last_name like ?
下面是我开发的代码.
Employee.java
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="EMPLOYEE_ID")
private Long employeeId;
@Column(name="FIRST_NAME")
private String firstName;
@Column(name="LAST_NAME")
private String lastName;
@Column(name="EMAIL_ID")
private String email;
@Column(name="STATUS")
private String status;
@Column(name="BIRTH_DATE")
private LocalDate birthDate;
@Column(name="PROJECT_ASSOCIATION")
private Integer projectAssociation;
}
注意:用户可以使用全局搜索搜索任何值,无论用户搜索什么,都应该能够看到数据,而不管数据类型.
Note: User can search for any value using on global search and whatever user search for, should be able to see data irrespective of data types.
EmployeeSpecification.java
public class EmployeeSpecification {
public static Specification<Employee> textInAllColumns(String text, List<String> attributes) {
if (!text.contains("%")) {
text = "%" + text + "%";
}
final String finalText = text;
return (root, query, builder) -> builder
.or(root.getModel().getDeclaredSingularAttributes().stream().filter(a -> {
if (a.getJavaType().getSimpleName().equalsIgnoreCase("String")) {
return true;
}else if(a.getJavaType().getSimpleName().equalsIgnoreCase("date")) {
return true;
}
else {
return false;
}
}).map(a -> builder.like(root.get(a.getName()), finalText)).toArray(Predicate[]::new));
}
}
但这种方法只考虑字符串字段,而不考虑日期和整数数据类型.我们该怎么做?
推荐答案
更改:
if(a.getJavaType().getSimpleName().equalsIgnoreCase("date"))
到:
if(a.getJavaType().getSimpleName().equalsIgnoreCase("LocalDate"))
这篇关于对单表的日期、整数和字符串数据类型字段执行多列搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!