当前位置: 首页 > 知识库问答 >
问题:

向Spring Data Repository方法的@Query传递可选参数

贺恩
2023-03-14
@RestController
@RequestMapping(value = SearchResource.URI)
public class PersonResource {

public static final String URI = "/person";

@Autowired
PersonRepository personRepository;

@GetMapping
public Collection<Person> findPersons(
    @RequestParam(value = "name", required = false) String name,
    @RequestParam(value = "birthDate", required = false) Long birthDate,
    @RequestParam(value = "town", required = false) Spring town) {

    Collection<Person> persons;

    if (name != null && birthDate == null && town == null) {
        persons = personRepository.findPersonByName(name);
    } else if (name != null && birthDate != null && town == null {
        persons = personRepository.findPersonByNameAndBirthDate(name, birthDate);
    } else if (name != null && birthDate != null && town != null {
        persons = personRepository.findPersonByNameAndBirthDateAndTown(name, birthDate, town);
    } else if (name == null && birthDate != null && town == null {
        persons = findPersonByBirthDate(birthDate);
    } else if
        ...
    }
    return persons;
}
}

是否有可能以更优雅的方式实现此功能?Spring数据在这种情况下提供任何支持吗?

共有1个答案

卜凯旋
2023-03-14

我使用带有Spring数据的QueryDSL解决了这个问题。在baeldung.com上有一个很好的教程。使用QueryDSL,spring数据查询只是PersonRepository.findAll(predicate);

您可以使用一个对象来表示多个请求参数,并将它们的类型声明为optional name; 等。

然后您可以构建谓词(假设您按照链接教程中的方法设置了内容):

Predicate predicate = new MyPredicateBuilder().with("name", ":", name.orElse(""))
.with("birthDate", ":", birthDate.orElse(""))
.with("town", ":", town.orElse(""))
.build();
 类似资料:
  • 如果没有声明相应的值,是否有可能动态忽略一些可选的参数?

  • 在JavaScript中,有没有一种方法可以将可选参数传递到函数中,如果它不是null的话?否则,根本不要传递此参数。 例如下面的函数,如果var_c为null,如何不插入c参数

  • 错误:不兼容的类型:DrawerListItem不能转换为Cap#1,其中Cap#1是一个新的类型变量:Cap#1从capture的capture扩展了BaseListItem?扩展基线 我不明白为什么这是错误的。,。我试着阅读了其他关于泛型类型和类型参数的文章,但它们似乎都没有解决这个问题。

  • 为了实现BrowserStack自动化,我已经将testNG与cucumber集成在一起,我希望在初始化浏览器之前为其设置功能。因此,当我通过testing.xml文件将功能作为参数传递给@before方法时,我会得到以下错误- *io.cucumber.java.invalidMethodSignatureException:用Before、After、BeforeStep或AfterStep注

  • 我是静态编程语言的新手,我发现静态编程语言不同于Java的特性之一是方法默认参数。https://kotlinlang.org/docs/functions.html#default-arguments 我正在创建一个简单的Kotlin应用程序,它将null值传递给具有2个不可为null的默认参数的方法,这会导致编译错误-类型不匹配:推断的类型是String?但应为字符串)。 一种解决方法是将方法

  • 问题内容: 最近,我与队友讨论了 在方法中使用可选参数的问题。 假设方法是 接受一个和 可选参数 ,它返回该目录中列出的书籍,如果还传递了类别,则仅返回该类别中的书籍。 冲突点是,验证是否为空检查。我认为不应对此进行空检查,因为它是可选参数。函数的调用者可以通过或,并且函数应在实现中处理两种情况。 我的意见是,对于可选参数,只会使方法的约定更加明确。只需查看方法签名即可知道此参数是可选的,不需要读