2010-11-11 66 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

相關問題