2012-07-24 75 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

相关问题