我在hibernate实例中有一个名为keywords的实体。它存储单词列表和每个单词出现的次数。言语不是唯一的。我想总结列表中每个单词的总和。我使用HQL
query select keyword, sum(keywordcount) from Keywords as Keywords group by keyword order by sum(keywordcount) desc
这给了我正确的结果。我遇到的问题是,当我提交此查询时,我得到一个java.lang.Object对象列表。有没有办法告诉HQL给我一个类型为关键字的对象列表,因为它们具有我想要的结构。
@Entity
@Table(name = "keywords", catalog = "akiradev")
public class Keywords implements java.io.Serializable {
// Fields
private Integer id;
private Documents documents;
private String keyword;
private Integer keywordcount;
// Constructors
/** default constructor */
public Keywords() {
}
/** full constructor */
public Keywords(Documents documents, String keyword, Integer keywordcount) {
this.documents = documents;
this.keyword = keyword;
this.keywordcount = keywordcount;
}
// Property accessors
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "document_id")
public Documents getDocuments() {
return this.documents;
}
public void setDocuments(Documents documents) {
this.documents = documents;
}
@Column(name = "keyword")
public String getKeyword() {
return this.keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
@Column(name = "keywordcount")
public Integer getKeywordcount() {
return this.keywordcount;
}
public void setKeywordcount(Integer keywordcount) {
this.keywordcount = keywordcount;
}
}
-------查询--------
public List<Keywords> getKeywordSum() {
try {
String queryString = "select keyword, sum(keywordcount) from Keywords as Keywords group by keyword order by sum(keywordcount) desc";
Query queryObject = getSession().createQuery(queryString);
List<Keywords> results = (List<Keywords>) queryObject.list();
return results;
} catch (RuntimeException re) {
log.error("finding Documents in descending time order failed", re);
throw re;
}
}
答案 0 :(得分:3)
在此处使用Keyword
作为返回类型没有多大意义,因为查询结果与关键字的身份不同。但是,您可以创建DTO来表示此查询的结果
public class KeywordStats {
private String keyword;
private int count;
public KeywordStats(String keyword, int count) { ... }
...
}
并使用构造函数语法从查询中返回它:
select new KeywordStats(keyword, sum(keywordcount)) from Keywords as Keywords group by keyword order by sum(keywordcount) desc
实际上,您可以使用相同的方法返回Keyword
,但我不推荐它,因为它是滥用实体对象。