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

时间:2015-07-31 09:44:03

标签: java hibernate jpa orm hql

有这个课程:

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 ]

1 个答案:

答案 0 :(得分:5)

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

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

在这种情况下,计数也没有多大意义,因为它将计算设备,产品和服务之间的笛卡尔积,所以我怀疑它是否有任何好处。