在Spring中,规范中对于”like”的使用不起作用。

huangapple go评论66阅读模式
英文:

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&lt;Plan&gt; hasOptionalName(String name) {
		return (root, query, criteriaBuilder) -&gt; name == null ?
				criteriaBuilder.conjunction() :
				criteriaBuilder.like(root.get(&quot;name&quot;), name);
	}
public Specification&lt;Plan&gt; 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(&quot;name&quot;), &quot;%&quot; + name + &quot;%&quot;)

Examples of like with criteriaBuilder: https://www.objectdb.com/java/jpa/query/jpql/string

huangapple
  • 本文由 发表于 2020年9月14日 18:24:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63882455.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定