2011-12-14 6 views
1

hibernate.iを使って最新のオブジェクトを見つけるのに過去3時間の間頭を悩ませていましたが、 null、またはcastTypeExcetpionhibernateのlast_modifiedフィールドに基づいて最新のレコードを取得する方法JPA(セッションインプリメンテーション)

public Content getMostRecentByCategoryAndGenre(Category category, Genre genre){ 
    logger.info("calling getMostRecentByCategoryAndGenre"); 
    logger.debug(category); 
    logger.debug(genre); 

    DetachedCriteria recentDate = DetachedCriteria.forClass(this.getPersistentClass()); 
    recentDate.setProjection(Projections.max("lastModified")); 

    Content recent = (Content) this.getSessionFactory().getCurrentSession().createCriteria(this.getPersistentClass()) 
      .add(Restrictions.eq("genre", genre)) 
      .add(Restrictions.eq("category", category)) 
      .setProjection(Projections.max("lastModified")) // gives cannot cast timestamp to com.bla.bla.bla.myproject 

     // .add(Property.forName("lastModified").eq(recentDate)) // this if uncommented and previous line commented gives null result 
      .uniqueResult(); 
    logger.debug(recent); 
    return recent; 
} 

私は正しく行っていないのですか?これを読んでくれてありがとう。

答えて

0

あなたはlastModifiedフィールド上の投影を使用しているため、結果にあなたがあなたのContentクラス型にキャストすることができない結果として、1行だけを取り出すようにしてlastModified値を持つ大きさ1のリストとしてのみlastModified値を取得します。最近のContentオブジェクトが必要な場合は、基準で投影を追加しないでください。

+0

クエリ1で、あなたは他のソリューションのplease.Projectionに私を指すfeedback.can遅れて申し訳ありませんが、コンテンツIDを投射することができ、私は –

+0

自分で行うことができ、最も簡単なの一つでありますlastModifiedの代わりに。そのIDを使用して、Contentオブジェクトを読み込むことができます。 – Pokuri

1

すべてのおかげでちょっと

// subquery to get the most recent date for this genre and category 
DetachedCriteria recentDate = DetachedCriteria.forClass(this.getPersistentClass()) 
    .add(Restrictions.eq("genre", genre)) 
    .add(Restrictions.eq("category", category)) 
    .setProjection(Projections.max("lastModified")); 

// get the content for the most recent date, genre and category 
Content recent = session.createCriteria(this.getPersistentClass()) 
     .add(Restrictions.eq("genre", genre)) 
     .add(Restrictions.eq("category", category)) 
     .add(Subqueries.eq("lastModified", recentDate)) 
     .uniqueResult<Content>(); 
関連する問題