【问题标题】:Spring specifications 'and' not working弹簧规格“和”不起作用
【发布时间】:2018-06-07 22:22:23
【问题描述】:

你好! 我正在尝试在运行时为数据网格构建自定义过滤器。 我正在使用 spring boot 和 vaadin 8 进行数据展示。 Vaadin 知识与这个问题无关。

我的表现如何: 我为过滤器构建了一个哈希图。

private HashMap<String, Specification<ARInteraction>> interactionSpecifications =
                                                                new HashMap<>();

每个过滤器文本字段都会向地图添加或删除规范:

TextField filterOwner = new TextField("Filter");
    filterOwner.addValueChangeListener(nv -> {
        if (StringUtils.isNotEmpty(nv.getValue())) {
            interactionSpecifications.put("owner", ARInteractionSpecifications
                             .withOwnerEmail(nv.getValue()));
        } else {
            interactionSpecifications.remove("owner");
        }
        refreshContent();
    });

当字段数据发生变化时,会在规格图中添加或替换(或删除)自定义规格。

然后我调用刷新数据视图内容,导致查询获取数据运行。

为了构建规范以查询数据,我只需通过在它们之间应用“与”操作来添加所有规范。

private Specification<ARInteraction> buildSpecification() {
    // No specs
    if (interactionSpecifications.isEmpty())
        return null;

    // Assembles all specs together
    Specification<ARInteraction> ret = null;
    for (Specification<ARInteraction> spec : interactionSpecifications.values()) {
        if (ret == null) {
            ret = Specification.where(spec);
        } else {
            ret.and(spec);
        }
    }
    return ret;
}

我预计会发生的事情是,在应用这两个过滤器的情况下,只会获取同时符合这两个规范的实体。

实际发生的情况是,如果我单独设置状态规范(此处未显示)它可以工作,如果我设置所有者电子邮件过滤器它也可以工作,但如果我同时设置,所有交互都来自该所有者显示为忽略状态过滤器

【问题讨论】:

    标签: spring spring-boot spring-data-jpa spring-data vaadin8


    【解决方案1】:

    你好吗?

    规范行为是不可变的,因此您应该使用 and 操作分配 ret 规范。 初学者的错误。

    for (Specification<ARInteraction> spec : interactionSpecifications.values()) {
        if (ret == null) {
            ret = Specification.where(spec);
        } else {
            ret = ret.and(spec); //Assign the ret so that specs are actually added.
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-10
      • 2013-11-29
      • 1970-01-01
      • 2011-01-02
      • 2011-06-22
      • 2013-05-05
      • 2014-02-15
      相关资源
      最近更新 更多