在JPQL查询中使用COUNT

时间:2013-10-07 13:08:08

标签: jpa jpql

我有以下JPQL查询:

    List<DestinationInfo> destinations = em.createQuery("SELECT NEW com.realdolmen.patuva.dto.DestinationInfo(d.name, d.continent, MIN(t.departureDate), MIN(t.pricePerDay), COUNT(t.id))" +
            " FROM Destination d, Trip t" +
            " WHERE d.continent = :continent " +
            " GROUP BY d.name, d.continent").setParameter("continent", searchedContinent).getResultList();

如果我运行此操作,我会收到错误:

javax.ejb.EJBTransactionRolledbackException: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [com.realdolmen.patuva.dto.DestinationsList]

如果我遗漏COUNT(t.id)并从DestinationInfo构造函数中删除该参数,则可以正常工作。为什么我无法将COUNT(t.id)映射到我的DestinationInfo DTO。

这是我的DestinationInfo课程:

public class DestinationInfo {
    private String name;
    private Continent continent;
    private Date earliestDeparture;
    private Integer totalNumTrips;
    private BigDecimal lowestPrice;

    public DestinationInfo(String name, Continent continent, Date earliestDeparture, BigDecimal lowestPrice, Integer totalNumTrips) {
        this.name = name;
        this.continent = continent;
        this.earliestDeparture = earliestDeparture;
        this.totalNumTrips = totalNumTrips;
        this.lowestPrice = lowestPrice;
    }

    // getters and setters
}

1 个答案:

答案 0 :(得分:2)

显然COUNT(t.id)会返回多个long类型。将DestinationInfo类更改为以下内容使其起作用:

public class DestinationInfo {
    private String name;
    private Continent continent;
    private Date earliestDeparture;
    private long totalNumTrips;
    private BigDecimal lowestPrice;

    public DestinationInfo(String name, Continent continent, Date earliestDeparture, BigDecimal lowestPrice, long totalNumTrips) {
        this.name = name;
        this.continent = continent;
        this.earliestDeparture = earliestDeparture;
        this.totalNumTrips = totalNumTrips;
        this.lowestPrice = lowestPrice;
    }

    // getters and setters
}