【问题标题】:Hibernate HQL JOIN - fetched association was not presentHibernate HQL JOIN - 获取的关联不存在
【发布时间】:2015-10-22 22:47:45
【问题描述】:

有这个课程:

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 ]

【问题讨论】:

    标签: java hibernate jpa orm hql


    【解决方案1】:

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

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

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

    【讨论】:

    • 可能是错字..我删除了“fetch”这个词并且它起作用了。
    • 无类型。您使用的是 JPQL 还是原生 SQL?此语法适用于 JPQL 或 HQL,不适用于原生 SQL 查询。
    • 它的 JPQL (JPA 2.x)..但是我遇到了同样的错误,“fetch”这个词出现了..我想“我不需要 fetch,因为我只想数数”(就像你提到)..然后我删除了“获取”并且它起作用了
    • 确实如此。我现在修改了答案。
    猜你喜欢
    • 2013-08-30
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    相关资源
    最近更新 更多