通过多个可选参数筛选API。

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

Filter api by multiple optional parameters

问题

我正在尝试使用多个可选参数来筛选存储库方法。但是我没有得到预期的结果。
以下是我的查询语句。

这里的访客实体包含多次访问,一次访问可以有一个联系人和一个时间段。

谢谢帮助。

@Query("select v from Visitor v join v.visits visits join visits.contactPerson cp where "
        + "v.firstName=:firstName or :firstName is NULL or :firstName = '' and "
        + "visits.approvalStatus=:approvalStatus or :approvalStatus is NULL or :approvalStatus = '' "
        + "and cp.firstName=:firstName or :firstName is NULL or :firstName = '' ")
public List<Visitor> findByFilter(@Param("firstName") String firstName,
        @Param("approvalStatus") String approvalStatus, @Param("firstName") String fName);
英文:

I am trying to filter repository method using multiple optional parameters. But I am not getting expected result.
Here is my query.

Here visitor entity contains multiple visits and one visits can have one contact person and one timeslot.

Thanks for the help

@Query(&quot;select v from Visitor v join v.visits visits join visits.contactPerson cp where &quot;
			+ &quot;v.firstName=:firstName or :firstName is NULL or :firstName = &#39;&#39; and &quot;
			+ &quot;visits.approvalStatus=:approvalStatus or :approvalStatus is NULL or :approvalStatus = &#39;&#39; &quot;
			+ &quot;and cp.firstName=:firstName or :firstName is NULL or :firstName = &#39;&#39; &quot;)
	public List&lt;Visitor&gt; findByFilter(@Param(&quot;firstName&quot;) String firstName,
			@Param(&quot;approvalStatus&quot;) String approvalStatus, @Param(&quot;firstName&quot;) String fName);

答案1

得分: 2

你需要添加括号,以便数据库能够按照你的意图理解你的查询:

 + &quot;(v.firstName=:firstName 或者 :firstName 为 NULL 或者 :firstName = &#39;&#39;) 并且 &quot;
 + &quot;(visits.approvalStatus=:approvalStatus 或者 :approvalStatus 为 NULL 或者 :approvalStatus = &#39;&#39;) &quot;
 + &quot;并且 (cp.firstName=:firstName 或者 :firstName 为 NULL 或者 :firstName = &#39;&#39;)&quot;

OR 运算符的优先级低于 AND,所以 a OR b AND c OR d 被解析为 a OR (b AND c) OR d,而不是 (a OR b) AND (c OR d)

英文:

You need to add parentheses to make the database understand your query the way you intend:

 + &quot;(v.firstName=:firstName or :firstName is NULL or :firstName = &#39;&#39;) and &quot;
 + &quot;(visits.approvalStatus=:approvalStatus or :approvalStatus is NULL or :approvalStatus = &#39;&#39;) &quot;
 + &quot;and (cp.firstName=:firstName or :firstName is NULL or :firstName = &#39;&#39;)&quot;

The OR operator has a lower precedence than AND so a OR b AND c OR d is parsed as a OR (b AND c) OR d, not as (a OR b) AND (c OR d).

huangapple
  • 本文由 发表于 2020年8月19日 17:54:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63484438.html
匿名

发表评论

匿名网友

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

确定