如何按相关实体的数量排序

时间:2013-12-12 17:32:15

标签: java hibernate sql-order-by hql

我有两个实体,文件和评论:

@Entity
@Table(name = "FILE")
@SuppressWarnings("serial")
@XmlRootElement
public class File implements Serializable {

    (...)
    private Set<Commentary> commentaries = new HashSet<Commentary>();

    (...)
    @OneToMany(mappedBy = "file")
    public Set<Commentary> getCommentaries() {
        return commentaries;
    }
}

@Entity
@Table(name = "COMMENTARY")
@SuppressWarnings("serial")
public class Commentary implements Serializable {

(...)
private File file;

(...)
@ManyToOne
@JoinColumn(name = "FILE_ID")
public File getFile() {
    return file;
}

我想创建一个HQL查询来获取文件,按照每个关联的评论数量对它们进行排序。我试过了:

SELECT f FROM FILE f WHERE f.name LIKE '%example%' ORDER BY COUNT(f.commentaries)
没有运气。如何使用HQL正确执行此操作?

2 个答案:

答案 0 :(得分:0)

试试这个

 SELECT f FROM FILE f WHERE f.name LIKE '%example%' ORDER BY COUNT(commentaries)

答案 1 :(得分:0)

我找到了答案。正确的HQL查询是:

SELECT f FROM FILE f WHERE f.name LIKE '%example%' ORDER BY size(f.commentaries)