gpt4 book ai didi

查询方法中的 Spring Data 可选参数

转载 作者:IT老高 更新时间:2023-10-28 13:44:21 29 4
gpt4 key购买 nike

我想在存储库层编写一些查询方法。此方法必须忽略空参数。例如:

List<Foo> findByBarAndGoo(Bar barParam, @optional Goo gooParam);

此方法必须在此条件下返回 Foo:

bar == barParam && goo == gooParam;

如果 gooParam 不为空。如果 gooParam 为空,则条件更改为:

bar == barParam;

有什么解决办法吗?有人可以帮我吗?

最佳答案

我不相信您可以使用方法名称方法来定义查询。来自文档(reference):

Although getting a query derived from the method name is quite convenient, one might face the situation in which either the method name parser does not support the keyword one wants to use or the method name would get unnecessarily ugly. So you can either use JPA named queries through a naming convention (see Using JPA NamedQueries for more information) or rather annotate your query method with @Query

我认为你这里有这种情况,所以下面的答案使用@Query 注释方法,这几乎与方法名称方法( reference )一样方便。

    @Query("select foo from Foo foo where foo.bar = :bar and "
+ "(:goo is null or foo.goo = :goo)")
public List<Foo> findByBarAndOptionalGoo(
@Param("bar") Bar bar,
@Param("goo") Goo goo);

关于查询方法中的 Spring Data 可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32728843/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com