簡體   English   中英

在 jpa 中使用 fetch 關系計數查詢

[英]Count query with fetch relation in jpa

這是我的實體:-

public class ArticleType extends BaseEntity implements Serializable
{
    private static final long   serialVersionUID    = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "art_typ_index")
    private Integer             artTypIndex;
    //@Basic(optional = false)
    @Column(name = "art_typ_code", nullable = false)
    private String              artTypCode;
    @OneToMany(mappedBy = "artArtTypIndex", fetch = FetchType.LAZY)
    private Set<Article>        articleSet;

    public ArticleType()
    {
    }

    public ArticleType(Integer artTypIndex)
    {
        this.artTypIndex = artTypIndex;
    }

    public ArticleType(Integer artTypIndex, String artTypCode)
    {
        this.artTypIndex = artTypIndex;
        this.artTypCode = artTypCode;
    }

    public Integer getArtTypIndex()
    {
        return artTypIndex;
    }

    public void setArtTypIndex(Integer artTypIndex)
    {
        this.artTypIndex = artTypIndex;
    }

    public String getArtTypCode()
    {
        return artTypCode;
    }

    public void setArtTypCode(String artTypCode)
    {
        this.artTypCode = artTypCode;
    }

    @XmlTransient
    public Set<Article> getArticleSet()
    {
        return articleSet;
    }

    public void setArticleSet(Set<Article> articleSet)
    {
        this.articleSet = articleSet;
    }   
}

我想檢查特定文章類型是否存在任何文章。
我試過這個HQL query :-

SELECT 
count(articleType.artTypIndex)
FROM
ArticleType articleType 
join fetch articleType.articleSet article
where articleType.artTypCode = ?

但是這個查詢給了我編譯錯誤:-

org.hibernate.QueryException:查詢指定連接提取,但選擇列表中不存在提取關聯的所有者 [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=article,role= com.alstom.autofie2.entity.ArticleType.articleSet,tableName=tbl_article,tableAlias=articleset1_,origin=tbl_article_typ e articletyp0_,columns={articletyp0_.art_typ_index ,className=com.alstom.autofie2.entity.Article}}]

我不明白是什么問題?
謝謝你。

問題是您正在選擇計數而不是實體,但您正在加入獲取。

您不需要使用您未獲取的實體急切地加載集合。

嘗試只使用加入。

或者這也可能有效

SELECT 
articleType,count(articleType.artTypIndex)
FROM
ArticleType articleType 
join fetch articleType.articleSet article
where articleType.artTypCode = ?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM