这是我的实体:-
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/