gpt4 book ai didi

java - 具有多个连接的 Spring Data JPA 多个可选搜索参数

转载 作者:行者123 更新时间:2023-11-30 06:05:46 29 4
gpt4 key购买 nike

我目前正在使用 Spring Boot 和 Spring Data JPA 连接到 Oracle 数据库。使用一个参数,我只使用 Spring Repository findById(Long id); 并且效果很好。另一方面,搜索对我来说要复杂得多。在我们的例子中,用户提供了一个带有多个可选搜索参数的嵌套 JSON 对象(此时我无法更改他们必须通过嵌套 JSON 发送数据的方式)。 JSON 输入对象如下所示:

{
"agent_filter": {
"first_name": "string",
"last_name": "string",
"agentNumber": "string",
"agentCode": "string"
},
"account": "string",
"status": "string",
"paid": "string",
"amount": "string",
"person_filter": {
"date_of_birth": "string",
"first_name": "string",
"last_name": "string",
"tax_id": "string"
}
}

所有搜索条件都是可选的(除了至少 1 个参数)

在后端我们有以下实体:

@Entity
Account{
@OneToMany
List<PersonRole> role;

@OneToMany
List<AgentRole> role;
}

@Entity
PersonRole{
String role;

Person person;
}

@Entity
AgentRole{
String role;

Agent agent;
}

@Entity
Person{...}

@Entity
Agent{...}

因此,为了提供搜索功能,我可以进行多个连接。我开始使用带有 @Query 符号的 JPQL,但我必须对每个参数执行 is null or 检查,这真是一团糟。我开始研究其他选项,我看到了有关 QueryDSL、标准、规范的内容,但我不确定应该关注和了解哪一个。不幸的是,我对这个主题知之甚少,我希望有人能为我指明正确的方向,以便很好地实现此搜索。谢谢!

最佳答案

查询DSL ftw!

当我遇到与您非常相似的问题时,让我给您举一个我的代码示例,因为我有一堆我想过滤的东西,其中很多可能是空的...

顺便说一句,如果您需要花哨的连接,那么您可能会直接使用查询 dsl。这些示例适用于 QueryDSL 3,因此您可能需要针对 QueryDSL 4 进行更改。因为您已经提到“为了提供搜索功能,我可以进行多个连接”,您可能需要直接使用 QueryDSL。

首先您创建自己和 BooleanBuilder,然后执行如下操作:

BooleanBuilder builder = new BooleanBuilder();
QContent content = QContent.content;
if (contentFilter.headlineFilter == null || contentFilter.headlineFilter.trim().length() == 0) {
// no filtering on headline as headline filter = null or blank
} else if (contentFilter.headlineFilter.equals(Filter.NULL_STRING)) {
// special case when you want to filter for specific null headline
builder.and(content.label.isNull());
} else {
try {
long parseLong = Long.parseLong(contentFilter.headlineFilter);
builder.and(content.id.eq(parseLong));
} catch (NumberFormatException e) {
builder.and(content.label.contains(contentFilter.headlineFilter));
}
}
if (contentFilter.toDate != null) {
builder.and(content.modifiedDate.loe(contentFilter.toDate));
}
if (contentFilter.fromDate != null) {
builder.and(content.modifiedDate.goe(contentFilter.fromDate));
}

因此,根据您是否拥有每个字段,您可以将其添加到过滤器中。

要使其正常工作,您需要生成查询 DSL 元数据 - 这是通过 com.mysema.query.apt.jpa.JPAAnnotationProcessor 注释处理器完成的。它生成上面的 QContent.content 内容。

BooleanBuilder 是 Predicate 的子类。

关于java - 具有多个连接的 Spring Data JPA 多个可选搜索参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45757570/

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