gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:57:42 25 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/32745673/

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