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

查看:28
本文介绍了查询方法中的 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;

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

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

bar == barParam;

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

Is there any solution? Can someone help me?

推荐答案

来不及回答.不确定 BarGoo 之间的关系.检查示例是否可以帮助您.

Too late to answer. Not sure about relationship between Bar and Goo. Check if Example can helps you.

它对我有用.我有类似的情况,实体 User 有一组属性,并且有 findAll 方法可以根据属性搜索用户(可选).

It worked for me. I have a similar situation, entity User have set of attributes and there is findAll method which search user based on attributes(which are optional).

示例,

  Class User{
    String firstName;
    String lastName;
    String id;
  }

  Class UserService{
     // All are optional
     List<User> findBy(String firstName, String lastName, String id){
        User u = new User();
        u.setFirstName(firstName);
        u.setLastName(lastName);
        u.setId(id);

        userRepository.findAll(Example.of(user));
        // userRepository is a JpaRepository class
     }
  }

这篇关于查询方法中的 Spring Data 可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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