QueryDsl 对地图字段键的 Web 查询概述试一些细节其他发现问题更换豆子从 http 参数创建地图搜索谓词

概述

鉴于

  • Spring Data JPA, Spring Data Rest, QueryDsl
  • 一个实体Meetup
    • 带字段Map<String,String> properties
      • 作为MEETUP_PROPERTY@ElementCollection
  • 一个MeetupRepository
    • 延伸QueryDslPredicateExecutor<Meetup>

我期待

的 Web 查询

GET /api/meetup?properties[aKey]=aValue

以仅返回具有指定键和值的属性条目的 Meetups:aKey=aValue。

但是,这对我不起作用。我错过了什么?

简单字段

简单的字段工作,如名称和描述:

GET /api/meetup?name=whatever

集合字段的工作方式,如参与者:

GET /api/meetup?participants.name=whatever

但不是此地图字段。

自定义 QueryDsl 绑定

我已尝试通过拥有存储库来自定义绑定

extend QuerydslBinderCustomizer<QMeetup>

并覆盖

customize(QuerydslBindings bindings, QMeetup meetup)

方法,但在命中方法时,lambda 中的绑定代码不是。customize()

编辑:了解到这是因为评估查询参数的方法不允许它与它内部保存的映射匹配 - 其中有您的自定义绑定。QuerydslBindingspathSpecs

一些细节

Meetup.properties field

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "MEETUP_PROPERTY", joinColumns = @JoinColumn(name = "MEETUP_ID"))
@MapKeyColumn(name = "KEY")
@Column(name = "VALUE", length = 2048)
private Map<String, String> properties = new HashMap<>();

自定义查询sl绑定

编辑:见上文;事实证明,这对我的代码没有任何作用。

public interface MeetupRepository extends PagingAndSortingRepository<Meetup, Long>,
                                          QueryDslPredicateExecutor<Meetup>,
                                          QuerydslBinderCustomizer<QMeetup> {

    @Override
    default void customize(QuerydslBindings bindings, QMeetup meetup) {
        bindings.bind(meetup.properties).first((path, value) -> {
            BooleanBuilder builder = new BooleanBuilder();
            for (String key : value.keySet()) {
                builder.and(path.containsKey(key).and(path.get(key).eq(value.get(key))));
            }
            return builder;
        });
}

其他发现

  1. QuerydslPredicateBuilder.getPredicate()要求尝试 2 种方法从 返回路径,以便它可以创建可以使用的谓词。QuerydslBindings.getPropertyPath()QuerydslAwareRootResourceInformationHandlerMethodArgumentResolver.postProcess()
    • 1 是查看自定义绑定。我看不到任何表达地图查询的方法
    • 2 是默认为 Spring 的 bean 路径。同样的表达问题。如何表达地图?因此,自动创建谓词看起来是不可能的。很好 - 我可以手动完成,如果我可以钩入QuerydslPredicateBuilder.getPredicate()QuerydslAwareRootResourceInformationHandlerMethodArgumentResolver.postProcess()

如何重写该类或替换 Bean?它被实例化并在 bean 声明中作为 Bean 返回。RepositoryRestMvcConfiguration.repoRequestArgumentResolver()

  1. 我可以通过声明我自己的bean来覆盖该bean,但它没有被使用。repoRequestArgumentResolver
    • 它被 s 覆盖。我无法通过设置它或来强制它。RepositoryRestMvcConfiguration@Primary@Ordered(HIGHEST_PRECEDENCE)
    • 可以通过显式组件扫描来强制它,但这也搞砸了Spring Boot的自动配置,因为它会导致在任何自动配置运行之前处理bean声明。除其他事项外,这会导致杰克逊以不需要的方式序列化响应。RepositoryRestMvcConfiguration.classRepositoryRestMvcConfiguration's

问题

好吧 - 看起来我期望的支持并不存在。

所以问题就变成了:我如何正确地覆盖豆子?repoRequestArgumentResolver

BTW - 是尴尬的非公开的。:/QuerydslAwareRootResourceInformationHandlerMethodArgumentResolver


答案 1

更换豆子

实施应用程序上下文感知

这就是我在应用程序上下文中替换 Bean 的方式。

感觉有点笨拙。我很想听到一个更好的方法来做到这一点。

@Configuration
public class CustomQuerydslHandlerMethodArgumentResolverConfig implements ApplicationContextAware {

    /**
     * This class is originally the class that instantiated QuerydslAwareRootResourceInformationHandlerMethodArgumentResolver and placed it into the Spring Application Context
     * as a {@link RootResourceInformationHandlerMethodArgumentResolver} by the name of 'repoRequestArgumentResolver'.<br/>
     * By injecting this bean, we can let {@link #meetupApiRepoRequestArgumentResolver} delegate as much as possible to the original code in that bean.
     */
    private final RepositoryRestMvcConfiguration repositoryRestMvcConfiguration;

    @Autowired
    public CustomQuerydslHandlerMethodArgumentResolverConfig(RepositoryRestMvcConfiguration repositoryRestMvcConfiguration) {
        this.repositoryRestMvcConfiguration = repositoryRestMvcConfiguration;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ((GenericApplicationContext) applicationContext).getBeanFactory();
        beanFactory.destroySingleton(REPO_REQUEST_ARGUMENT_RESOLVER_BEAN_NAME);
        beanFactory.registerSingleton(REPO_REQUEST_ARGUMENT_RESOLVER_BEAN_NAME,
                                      meetupApiRepoRequestArgumentResolver(applicationContext, repositoryRestMvcConfiguration));
    }

    /**
     * This code is mostly copied from {@link RepositoryRestMvcConfiguration#repoRequestArgumentResolver()}, except the if clause checking if the QueryDsl library is
     * present has been removed, since we're counting on it anyway.<br/>
     * That means that if that code changes in the future, we're going to need to alter this code... :/
     */
    @Bean
    public RootResourceInformationHandlerMethodArgumentResolver meetupApiRepoRequestArgumentResolver(ApplicationContext applicationContext,
                                                                                                     RepositoryRestMvcConfiguration repositoryRestMvcConfiguration) {
        QuerydslBindingsFactory factory = applicationContext.getBean(QuerydslBindingsFactory.class);
        QuerydslPredicateBuilder predicateBuilder = new QuerydslPredicateBuilder(repositoryRestMvcConfiguration.defaultConversionService(),
                                                                                 factory.getEntityPathResolver());

        return new CustomQuerydslHandlerMethodArgumentResolver(repositoryRestMvcConfiguration.repositories(),
                                                               repositoryRestMvcConfiguration.repositoryInvokerFactory(repositoryRestMvcConfiguration.defaultConversionService()),
                                                               repositoryRestMvcConfiguration.resourceMetadataHandlerMethodArgumentResolver(),
                                                               predicateBuilder, factory);
    }
}

从 http 参数创建地图搜索谓词

Extend RootResourceInformationHandlerMethodArgumentResolver

这些是代码片段,它们基于 http 查询参数创建我自己的 Map 搜索谓词。再次 - 很想知道更好的方法。

该方法调用:postProcess

        predicate = addCustomMapPredicates(parameterMap, predicate, domainType).getValue();

就在引用传递到构造函数并返回之前。predicateQuerydslRepositoryInvokerAdapter

这是该方法:addCustomMapPredicates

    private BooleanBuilder addCustomMapPredicates(MultiValueMap<String, String> parameters, Predicate predicate, Class<?> domainType) {
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        parameters.keySet()
                  .stream()
                  .filter(s -> s.contains("[") && matches(s) && s.endsWith("]"))
                  .collect(Collectors.toList())
                  .forEach(paramKey -> {
                      String property = paramKey.substring(0, paramKey.indexOf("["));
                      if (ReflectionUtils.findField(domainType, property) == null) {
                          LOGGER.warn("Skipping predicate matching on [%s]. It is not a known field on domainType %s", property, domainType.getName());
                          return;
                      }
                      String key = paramKey.substring(paramKey.indexOf("[") + 1, paramKey.indexOf("]"));
                      parameters.get(paramKey).forEach(value -> {
                          if (!StringUtils.hasLength(value)) {
                              booleanBuilder.or(matchesProperty(key, null));
                          } else {
                              booleanBuilder.or(matchesProperty(key, value));
                          }
                      });
                  });
        return booleanBuilder.and(predicate);
    }

    static boolean matches(String key) {
        return PATTERN.matcher(key).matches();
    }

和模式:

    /**
     * disallow a . or ] from preceding a [
     */
    private static final Pattern PATTERN = Pattern.compile(".*[^.]\\[.*[^\\[]");

答案 2

我花了几天时间研究如何做到这一点。最后,我只是手动添加到谓词中。这个解决方案感觉简单而优雅。

因此,您可以通过以下方式访问地图

GET /api/meetup?properties.aKey=aValue

在控制器上,我注入了请求参数和谓词。

public List<Meetup> getMeetupList(@QuerydslPredicate(root = Meetup.class) Predicate predicate,
                                                @RequestParam Map<String, String> allRequestParams,
                                                Pageable page) {
    Predicate builder = createPredicateQuery(predicate, allRequestParams);
    return meetupRepo.findAll(builder, page);
}

然后,我只是简单地解析查询参数并添加包含

private static final String PREFIX = "properties.";

private BooleanBuilder createPredicateQuery(Predicate predicate, Map<String, String> allRequestParams) {
    BooleanBuilder builder = new BooleanBuilder();
    builder.and(predicate);
    allRequestParams.entrySet().stream()
            .filter(e -> e.getKey().startsWith(PREFIX))
            .forEach(e -> {
                var key = e.getKey().substring(PREFIX.length());
                builder.and(QMeetup.meetup.properties.contains(key, e.getValue()));
            });
    return builder;
}

推荐