2012-07-24 11 views
39

私のコードでCriteria Queryを使用しています。それはいつも発生するselect * from ...Hibernate Criteria特定の列を取得するクエリ

代わりに、そのフィールドが大量のデータをバイトとして格納しているので、私のクエリから1つの列(フィールド)を無視したい。そしてそれはパフォーマンスの問題を引き起こします。

これは誰でも考えられますか?


一部更新

私は私のクエリで投影を追加し、それは、クエリのような...

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

+0

@cingulataはい可能です。この記事をチェックしてください。http://www.objectdb.com/java/jpa/query/jpql/select –

0

このクラスに基づいて別のエンティティをマッピングできます(2つを区別するためにentity-nameを使用する必要があります)。もう1つはdtoのようなものです(dto has design issuesを忘れないでください)。 2番目のものを読み取り専用として定義し、これが通常のエンティティではないことを明確にするために適切な名前を付ける必要があります。 ちょうどいくつかの列を選択すると、投影と呼ばれるので、それと簡単になるGoogleと。

代替 - あなたはあなたが返すように希望する列を指定するために投影

+0

http://www.mkyong.com/hibernate/hibernate-named-query-例/ –

関連する問題