java - Join 上的谓词不起作用

标签 java sql jpa criteria-api

如果我使用连接在条件查询中创建谓词,我将不会得到任何结果。当我将 Game 表用作根时,相同的谓词返回实体。

工作查询:

    CriteriaQuery<Game> query = cb.createQuery(Game.class);
    Root<Game> root = query.from(Game.class);

    List<Predicate> predicates = new LinkedList<Predicate>();
    if(!selectedPlatforms.isEmpty()) {
        predicates.add(root.get(Game_.type).in(TypeConverter.convert(selectedPlatforms)));
    }

    if(!selectedCategories.isEmpty()) {
        Join<Game, String> collection = root.join(Game_.categories);
        predicates.add(collection.in(cb.literal(selectedCategories)));
    }

    if(!selectedGames.isEmpty()) {
        predicates.add(cb.isTrue(root.get(Game_.name).in(selectedGames)));
    }


    query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
    games = em.createQuery(query).getResultList();

无效查询:

    CriteriaQuery<Hit> query = cb.createQuery(Hit.class);
    List<Predicate> predicates = new LinkedList<>();
    Date startDate = null;
    Date endDate = null;

    Root<Hit> hitRoot = query.from(Hit.class);
    switch (time) {
        case "Week":
            startDate = new DateTime().withWeekOfWeekyear(timeValue).withDayOfWeek(DateTimeConstants.MONDAY).toDate();
            endDate = new DateTime().withWeekOfWeekyear(timeValue+1).withDayOfWeek(DateTimeConstants.SUNDAY).toDate();
    }
    predicates.add(cb.and(cb.greaterThanOrEqualTo(hitRoot.<Date>get("hitDate"), startDate), cb.lessThanOrEqualTo(hitRoot.<Date>get("hitDate"), endDate)));

    Join<Hit, Game> gameJoin = hitRoot.join("game", JoinType.LEFT);
    if(!selectedPlatforms.isEmpty()) {
        predicates.add(gameJoin.get(Game_.type).in(TypeConverter.convert(selectedPlatforms)));
    }

    if(!selectedCategories.isEmpty()) {
        Join<Game, String> collection = gameJoin.join(Game_.categories);
        predicates.add(collection.in(cb.literal(selectedCategories)));
    }

    if(!selectedGames.isEmpty()) {
        predicates.add(cb.isTrue(gameJoin.get(Game_.name).in(selectedGames)));
    }

    query.groupBy(hitRoot.get("hitDate"), hitRoot.get("shop"));
    query.orderBy(cb.asc(hitRoot.get("shop")));
    query.where(predicates.toArray(new Predicate[predicates.size()]));

    List<Hit> results = em.createQuery(query).getResultList();

以下部分负责不返回任何匹配实体。相同的部分只是应用于 Root 而不是 Join ,就像在第一个查询中一样返回 machting entites。没有这部分,其他一切都在工作。

    if(!selectedGames.isEmpty()) {
        predicates.add(cb.isTrue(gameJoin.get(Game_.name).in(selectedGames)));
    }

最佳答案

问题通过在“运行”模式下重新启动应用程序服务器自行解决。

关于java - Join 上的谓词不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19192183/

相关文章:

java - 在 JPA 中保留 map

java - Wicket 口和数据库访问的最佳实践

java - 如何按给定顺序返回数组元素?

java - NetBeans 7.0 是否内置了对 spring 3.0 的支持?

java - 构建 Ionic 项目时出现 JVM 错误

sql - 按名字和姓氏搜索的 Postgresql 查询,我应该创建哪些索引?

sql - 选择命中序列的查询消耗大量数据

java - JAXB 与 IDEA + Android 插件上的数据绑定(bind)冲突

php - 根据 PHP 的受欢迎程度显示帖子的最佳方法是什么?

java - 在 JPA-SQL(或 HQL)查询中兼容的 Hibernate Composite UserType