java - jpa 中使用 fetch 关系对查询进行计数

标签 java hibernate jpa sql-server-2012

这是我的实体:-

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 查询 :-

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

但是这个查询给了我编译错误:-

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=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}}]

我不明白问题出在哪里?
谢谢。

最佳答案

问题是您正在选择计数而不是实体,但您正在连接获取。

您不需要急切地使用未提取的实体加载集合。

尝试仅使用 join。

或者这也可能有效

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

关于java - jpa 中使用 fetch 关系对查询进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28237915/

相关文章:

java - 如何阻止cmd.bat关闭——java jar应用程序

java - 无法运行总计

java - 关于hibernate注解的问题

java - 在 hibernate 中为实体 bean 属性编写注释

java - 如何使用 criteriaBuilder 检查集合中的实体是否包含特定值?

从文件读取时出现 java.util.InputMismatchException

java - 通过同步方法返回值同步块(synchronized block)的跨度

spring - 我可以通过 Tomcats web xml (../webapps/WEB-INF/web.xml) 初始化 Spring 吗?

java - 我如何为给定的 SQL 查询编写 JPA 查询

java - EntityManager 刷新