查询方法中的Spring Data可选参数 [英] Spring Data optional parameter in query method

查看:158
本文介绍了查询方法中的Spring Data可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to write some query methods in repository layer. This method must ignore null parameters. For example:

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

这个方法必须通过这个条件返回Foo:

This method must be return Foo by this condition:

bar == barParam && goo == gooParam;

if gooParam not null。如果gooParam为null,则条件变为:

if gooParam not null. if gooParam was null then condition change to:

bar == barParam;

有没有解决方法?有人可以帮我吗?

Is there any solution? Can someone help me?

推荐答案

我不相信你可以用方法名称方法来查询定义。从文档(
$ b

I don't believe you'll be able to do that with the method name approach to query definition. From the documentation (reference):


尽管从方法名得到的查询是相当
方便,可能会遇到这样的情况,即
名称解析器不支持要使用的关键字,或者
方法的名称会不必要地变得很难看。因此,您可以通过命名约定使用JPA命名
查询(请参阅使用JPA NamedQueries查询
的更多信息),或者使用@Query注释查询方法

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 ) 。

I think you have that situation here, so the answer below uses the @Query annotation approach, which is almost as convenient as the method name approach (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可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆