SubQuery <date>不能在Criteria API </date>中分组

时间:2015-04-02 22:22:46

标签: java hibernate jpa criteria-api

您好groupBy使用subQuery时遇到问题 数据库结果

_______________________
|  id  |  departure   |
|______|______________|
| 99   |   00:54      |
|______|______________|
| 100  |   00:54      |
|______|______________|

我需要

|  id  |  departure   |
|______|______________|
| 99 or|   00:54      |
|_100__|______________|

我使用分组

public List<TripSchedule> findByDay(Date dateTime, Integer day, Long trainId) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<TripSchedule> criteriaQuery = builder.createQuery(TripSchedule.class);

    Root<TripSchedule> root = criteriaQuery.from(TripSchedule.class);
    Join<TripSchedule, Train> trains = root.join(TripSchedule_.trains, JoinType.LEFT);

    Expression<Date> departure = root.get(TripSchedule_.departure);
    Subquery<Date> subQuery = criteriaQuery.subquery(Date.class);

    criteriaQuery.select(root).distinct(true);
    Root<TripSchedule> dateRoot = subQuery.from(TripSchedule.class);

    subQuery.select(departure).distinct(true);
    Predicate predicate = builder.conjunction();

    if (dateTime != null) {
        predicate = builder.and(predicate, builder.greaterThanOrEqualTo(root.get(TripSchedule_.departure), dateTime));
    }

    if (trains != null) {
        predicate = builder.and(predicate, builder.equal(trains.get(Train_.id), trainId));
    }

    if (day != null) {
        predicate = initPredicateByDay(root, predicate, builder, day);
    }

    subQuery.where(predicate);
    subQuery.groupBy(dateRoot.get(TripSchedule_.departure));
    criteriaQuery.select(root).where(builder.in(root.get(TripSchedule_.departure)).value(subQuery));
    TypedQuery<TripSchedule> tq = entityManager.createQuery(criteriaQuery);
    return tq.getResultList();
    // return entityManager.createQuery(criteriaQuery).getResultList();
}

我不知道为什么谓词工作正常但groupBy无效。

这是生成sql:

select
    distinct tripschedu0_.id as id1_13_,
    tripschedu0_.name as name2_13_,
    tripschedu0_.departure as departur3_13_,
    tripschedu0_.friday as friday4_13_,
    tripschedu0_.monday as monday5_13_,
    tripschedu0_.period as period6_13_,
    tripschedu0_.saturday as saturday7_13_,
    tripschedu0_.sunday as sunday8_13_,
    tripschedu0_.thursday as thursday9_13_,
    tripschedu0_.tuesday as tuesday10_13_,
    tripschedu0_.wednesday as wednesd11_13_ 
from
    TripSchedule tripschedu0_ 
left outer join
    Train_TripSchedule trains1_ 
        on tripschedu0_.id=trains1_.SCHEDULE_ID 
left outer join
    Train train2_ 
        on trains1_.TRAIN_ID=train2_.id 
where
    tripschedu0_.departure in (
        select
            distinct tripschedu0_.departure 
        from
            TripSchedule tripschedu3_ 
        where
            1=1 
            and tripschedu0_.departure>=? 
            and train2_.id=5 
            and tripschedu0_.sunday=? 
        group by
            tripschedu3_.departure
    )

0 个答案:

没有答案