Hibernate HQL JOIN - 获取的关联不存在

Hibernate HQL JOIN - fetched association was not present

有这个class:

public class Device implements java.io.Serializable {

    private Set<Product> products = new HashSet<Product>(0);
    private Set<Service> services = new HashSet<Service>(0);

    @OneToMany (fetch = FetchType.LAZY, mappedBy = "device", cascade = {     CascadeType.REMOVE })
    @Cascade({ org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
    @OrderBy("id")
    public Set<Product> getProducts() {
        return this.products;
    }

   @OneToMany (fetch = FetchType.LAZY, mappedBy = "device", cascade = {     CascadeType.REMOVE })
    @Cascade({ org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
    @OrderBy("id")
    public Set<Service> getServices() {
        return this.services;
    }    
}

我想使用带关联和连接的 Hibernate 查询语言执行此查询,hibernate 的版本是 3.2.6

@Override
    public int numberofProductsOrServices(String licenseNumber) {

        String queryString = "select count(*) as n from Device dev "
                + " left join fetch dev.products products "
                + " left join fetch dev.services services ";


        try {

            Query query = getEntityManager().createQuery(queryString);          
            return (int)query.getSingleResult();

        } catch (RuntimeException re) {
            log.error( re);
            throw re;
        }       
    }

但是我得到了这个奇怪的错误:

java.lang.IllegalArgumentException: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=products,role=com.domain.Device.products,tableName=T_PRODUCT,tableAlias=products1_,origin=T_DEVICE applicatio0_,colums={applicatio0_.ID ,className=eu.europa.ec.env.ecolabel.domain.Product}}] [select count(*) as n from com.domain.Device app  left join fetch app.products products  left join fetch app.services services ]

如果您只是想统计条目数,则无需加入fetch。您需要将查询更改为:

String queryString = 
    "select count(*) as n from Device dev"
    + " left join dev.products "
    + " left join dev.services ";

在这种情况下计数也没有多大意义,因为它会计算设备、产品和服务之间的笛卡尔积,所以我怀疑它有什么用。