用途
- 可以结合@JpaSelectOperator 使用
- 可快速的完成单表的复杂查询
- 根据入参对象进行查询条件的封装
- where field = value and field2 like ‘%value%’ or field3 <> value
用法示例
使用单例构造 SpecificationUtil
- and 为 key写死示例
- and2为根据实体获取key的示例
SpecificationUtil<User> instance = SpecificationUtil.getInstance();
Specification<User> and = instance.like("address", "重庆", true)
.and(instance.eq("name", "用户", true)
.or(instance.eq("loginPwd", "123", true))
.or(instance.eq("phone", "123", true))
.or(instance.eq("userNo", "123", true))
);
Specification<User> and2 = instance.like(User::getAddress, "重庆", true)
.and(instance.eq(User::getName, "用户", true)
.or(instance.eq(User::getLoginPwd, "123", true))
.or(instance.eq(User::getPhone, "123", true))
.or(instance.eq(User::getUserNo, "123", true))
);
userService.getJpaBasicsDao().findAll(and).forEach(System.out::println);
直接使用 Specification
构建查询条件
public static Specification<User> name() {
return (root, query, builder) -> builder.like(root.get("name"), "%用户%");
}
public static Specification<User> loginPwd() {
return (root, query, builder) -> builder.like(root.get("loginPwd"), "123");
}
public static Specification<User> address() {
return (root, query, builder) -> builder.like(root.get("address"), "重庆");
}
public static Specification<User> phone() {
return (root, query, builder) -> builder.like(root.get("phone"), "123");
}
public static Specification<User> userNo() {
return (root, query, builder) -> builder.like(root.get("phone"), "123");
}
使用示例
userService.getJpaBasicsDao().findAll(
address().and(
loginPwd().or(phone()).or(name())
).or(
loginPwd().and(
phone().or(name())
)
)
).forEach(System.out::println);