2010-11-11 88 views
0

我在一个名为关键字的hibernate实例中有一个实体。它存储单词列表和每个单词出现的次数。单词不是唯一的。我想总结列表中每个单词的总数。我使用HQL我可以为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; 
    } 
} 

回答

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小号,但我不会推荐它,因为它是对实体对象的滥用。

+0

谢谢axvat。你的解决方案并不是我所想的,但实际上比我想要的要明智得多:)你观察我希望将结果强制到实体对象中,但使用DTO是一个更简洁的解决方案。 – 2010-11-11 12:59:55

相关问题