英文:
Usage of like in Specification is not working in Spring
问题
我在数据库中有一个名称为“New Plan”的计划,但每次我使用参数“New”进行查询时,它都不会给我返回结果。(根据使用 like
应该返回结果)
我构建规范的方式有问题吗?
谢谢
规范:
public Specification<Plan> hasOptionalName(String name) {
return (root, query, criteriaBuilder) -> name == null ?
criteriaBuilder.conjunction() :
criteriaBuilder.like(root.get("name"), name);
}
public Specification<Plan> buildSpecification(Long id, String name, PlanStatus status) {
return planSpecification.withId(id)
.and(planSpecification.withStatus(status))
.and(planSpecification.hasOptionalName(name));
}
但结果不会返回“New Plan”,但当我移除筛选条件时,它会被返回。
英文:
I have in my db a Plan with a name
"New Plan" but everytime I query with the parameter "New", it won't give me the results. (Which it should return since I'm using like
)
Is there something wrong on how I constructed my Specification?
Thank you
Specification:
public Specification<Plan> hasOptionalName(String name) {
return (root, query, criteriaBuilder) -> name == null ?
criteriaBuilder.conjunction() :
criteriaBuilder.like(root.get("name"), name);
}
public Specification<Plan> buildSpecification(Long id, String name, PlanStatus status) {
return planSpecification.withId(id)
.and(planSpecification.withStatus(status))
.and(planSpecification.hasOptionalName(name));
}
But the results won't return "New Plan" but when I remove the filter, it will be returned.
答案1
得分: 0
criteriaBuilder.like()
不会为您添加%
,所以您在那里进行的操作是在寻找一个名为New
的计划(在这种情况下确切是这样)。您应该在您寻找的字符串上添加%
,类似于以下方式:
criteriaBuilder.like(root.get("name"), "%" + name + "%")
使用criteriaBuilder进行like查询的示例:https://www.objectdb.com/java/jpa/query/jpql/string
英文:
criteriaBuilder.like()
doenst put the %
for you, so wath your are doing there is looking for a plan that is call New
(exactly is this case) you should add the %
on the string you are looking for, something like that:
criteriaBuilder.like(root.get("name"), "%" + name + "%")
Examples of like with criteriaBuilder: https://www.objectdb.com/java/jpa/query/jpql/string
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论