gpt4 book ai didi

java - 在 Spring Data 中为同一 QueryDSL 路径创建多个别名

转载 作者:IT老高 更新时间:2023-10-28 13:05:37 24 4
gpt4 key购买 nike

我有一个通用的 Spring Data 存储库接口(interface),它扩展了 QuerydslBinderCustomizer,允许我自定义查询执行。我正在尝试扩展默认存储库实现中内置的基本相等测试,以便我可以使用 Spring Data REST 执行其他查询操作。例如:

GET /api/persons?name=Joe%20Smith  // This works by default
GET /api/persons?nameEndsWith=Smith // This requires custom parameter binding.

我遇到的问题是我创建的实体路径的每个别名似乎都覆盖了前面的别名绑定(bind)。

@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable>
extends PagingAndSortingRepository<T, ID>, QueryDslPredicateExecutor<T>, QuerydslBinderCustomizer {

@Override
@SuppressWarnings("unchecked")
default void customize(QuerydslBindings bindings, EntityPath entityPath){

Class<T> model = entityPath.getType();
Path<T> root = entityPath.getRoot();
for (Field field: model.getDeclaredFields()){
if (field.isSynthetic()) continue;
Class<?> fieldType = field.getType();
if (fieldType.isAssignableFrom(String.class)){
// This binding works by itself, but not after the next one is added
bindings.bind(Expressions.stringPath(root, field.getName()))
.as(field.getName() + "EndsWith")
.first((path, value) -> {
return path.endsWith(value);
});
// This binding overrides the previous one
bindings.bind(Expressions.stringPath(root, field.getName()))
.as(field.getName() + "StartsWith")
.first((path, value) -> {
return path.startsWith(value);
});
}
}
}
}

是否可以为同一个字段创建多个别名?这可以通过通用方式完成吗?

最佳答案

您可以通过这种方式创建绑定(bind)到 QueryDSL 的 transient 属性:

@Transient
@QueryType(PropertyType.SIMPLE)
public String getNameEndsWith() {
// Whatever code, even return null
}

如果您使用的是 QueryDSL 注解处理器,您将在元数据 Qxxx 类中看到“nameEndsWith”,因此您可以像绑定(bind)任何持久化属性一样绑定(bind)它,但无需持久化它。

关于java - 在 Spring Data 中为同一 QueryDSL 路径创建多个别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41667317/

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