将groupBy应用于Spring规范查询

时间:2015-07-06 15:25:07

标签: spring spring-data

我正在使用Spring规范驱动的存储库构建一个简单的搜索引擎。问题是我做了以重复记录结束的连接查询,我需要应用groupBy限制,如果我在我的规范中调用.groupBy,则不应用于结果查询。我怎样才能实现这样的分组?

最小的例子可以指定如下:

存储库

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface EntityRepository implements JpaSpecificationExecutor<Entity> {}

规范

import org.springframework.data.jpa.domain.Specification;

public class DummyEntitySpecification implements Specification<Entity> {
    public Predicate toPredicate(Root<Entity> root, CriteriaQuery<?> criteriaQuery,
            CriteriaBuilder builder) {
        // So from here i get results with repeated main entity data, but actually
        // i need to filter results that has presence of related subentities of
        // some sort
        From join = root.join("SubEntity");
        // though i call groupBy here, Spring internally uses another query
        // instance, which doesn't inherit grouping
        criteriaQuery.groupBy(root.get("id"));
        return criteriaBuilder.ge(join.get("id"), 1);
    }
}

呼叫

public class Anyclass {

    @Autowired
    private EntityRepository entityRepository;

    public void uselessSearch() {
        // this may return several entities with id = 1, for example
        entityRepository.findAll(new DummyEntitySpecification());
    }
}

0 个答案:

没有答案