2013-07-31 40 views
0

我與Hibernate的標準建立了一個查詢(我會告訴你只有 「主要」 部分):Hibernate的標準:DTO作爲實體

Criteria criteria = sessionProvider.get().createCriteria(User.class); 
// Add other stuff to the query like joins, group-bys, order-bys etc. 
// In the projection list add the "id" of the user. 
projectionList.add(Projections.property("id"), "id"); 
// finally using same entity class User as dto 
criteria.setResultTransformer(Transformers.aliasToBean(User.class)); 

所以我終於可以做:

List<User> users = criteria.list(); 

問題當我嘗試從這個實體加載值時就會出現。例如:

users.get(0).getFirstName(); 

返回null。所以基本上由Transformers.aliasToBean創建的像「dtos」的實體通過投影僅接收到「id」並不像get/load/etc加載的普通實體那樣工作。

有什麼辦法讓這些dto「工作」爲實體嗎?

+1

不要設置'Projection'或'ResultTransformer','sessionProvider.get()。createCriteria(User.class).list()'。 –

+0

如果我不使用它們,它會返回一個Object [],其值與相關的groupbys相關。 – Randomize

+0

在這種情況下,我認爲你需要在那裏發佈更多的查詢,以便我們可以計算出它實際返回的內容...... –

回答

0

似乎在projectionList中傳遞參數是錯誤的,您需要像這樣修改projectionList。

Criteria criteria = sessionProvider.get().createCriteria(User.class); 
//Add other stuff to the query like joins, group-bys, order-bys etc. 

//In the projection list add the columns name which are mapped with the entity 
ProjectionList projectionList = Projections.projectionList(); 
projectionList.add(Projections.property("id")); 
projectionList.add(Projections.property("firstName")); 
criteria.setProjection(projectionList); 

List<User> results = criteria.list(); 

//output results 
for(User user : results) { 
    user.getFirstName();   
}