2012-07-24 73 views
39

我在我的代碼中使用Criteria Query。它總是會觸發select * from ...Hibernate Criteria查詢獲取特定列

相反,我想忽略從我的查詢中的一列(字段),因爲該字段有大量數據以字節存儲。並導致性能問題。

任何人都可以給出一個想法嗎?


一些更新

我在查詢中添加投影,它創造了一個查詢像...

select 
    this_.TEMPLATE_ID as y0_, 
    this_.TEMPLATE_NAME as y1_, 
    this_.CREATE_DATE as y2_, 
    this_.UPDATE_DATE as y3_, 
    this_.STATUS_CODE as y4_, 
    this_.USER_ID as y5_, 
    this_.UPDATED_BY as y6_, 
    this_.CATEGORY_ID as y7_, 
    this_.PRACTICE_ID as y8_ 
from 
    templates this_ 
inner join 
    user user1_ 
     on this_.USER_ID=user1_.USER_ID 
inner join 
    template_categories category2_ 
     on this_.CATEGORY_ID=category2_.CATEGORY_ID 
where 
    y4_=? 
    and y8_=? 
    and y5_ in (
     ?, ? 
    ) 
order by 
    y1_ asc limit ? 

而現在的問題是一樣.. Unknown column 'y4_' in 'where clause' 和同樣的錯誤對於y8_,y5_意味着所有關閉的地方都給出錯誤。

我修改它來查詢像...

select 
    this_.TEMPLATE_ID as y0_, 
    this_.TEMPLATE_NAME as y1_, 
    this_.CREATE_DATE as y2_, 
    this_.UPDATE_DATE as y3_, 
    this_.STATUS_CODE as y4_, 
    this_.USER_ID as y5_, 
    this_.UPDATED_BY as y6_, 
    this_.CATEGORY_ID as y7_, 
    this_.PRACTICE_ID as y8_ 
from 
    templates this_ 
inner join 
    user user1_ 
     on this_.USER_ID=user1_.USER_ID 
inner join 
    template_categories category2_ 
     on this_.CATEGORY_ID=category2_.CATEGORY_ID 
where 
    this_.STATUS_CODE=1 
    and this_.PRACTICE_ID=1 
    and this_.USER_ID in (
     1, 2 
    ) 
order by 
    y1_ asc limit ? 

和它的工作。但我不知道如何在HQL中修改它?

回答

81

使用Projections指定您想返回的列字段列表命名查詢。

SQL查詢

SELECT user.id, user.name FROM user; 

休眠替代

Criteria cr = session.createCriteria(User.class) 
    .setProjection(Projections.projectionList() 
     .add(Projections.property("id"), "id") 
     .add(Projections.property("Name"), "Name")) 
    .setResultTransformer(Transformers.aliasToBean(User.class)); 

    List<User> list = cr.list(); 
+0

是否可以對JPA執行相同的操作? – cingulata 2017-07-25 16:04:38

+0

@cingulata是的,這是可能的。檢查這篇文章http://www.objectdb.com/java/jpa/query/jpql/select – 2017-08-28 10:26:16

0

你可以映射另一個基於這個類的實體(你應該使用entity-name來區分這兩個),第二個將是dto(不要忘記dto has design issues)。 你應該將第二個定義爲只讀,並給它一個好名字,以明確這不是一個常規實體。 順便選擇只有幾列被稱爲投影,所以谷歌與它會更容易。

選擇 - 你可以創建你需要(你把他們的選擇),或者使用標準與投影

+0

http://www.mkyong.com/hibernate/hibernate-named-query-示例/ – 2013-07-31 05:11:30

相關問題