Thursday, February 10, 2011

Limit associated entities loaded through a Hibernate Criteria

Is it possible to limit the number of associated entities fetched through a Hibernate Criteria? Consider the following two entities:

@Entity
public class History {

  @OneToMany
  private List<Entry> entries

  ...

}

@Entity
public class Entry {

  @ManyToOne
  private History history;
  private DateTime date;

  ...

}

I need to use a Criteria to fetch all History entities, but to only return the latest Entry entity for each History entity. In other words, each History's entries field should only contain the latest Entry for that History entity. I need to do something like an order by and limit on Entry even though I am querying (with Criteria) on History.

Is this possible and if so how?

  • This can be done by calling the following on the Criteria:

    criteria.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP)
    

    With this ResultTransformer, only those associated entities that match the restrictions will be populated.

    From Zecrates

0 comments:

Post a Comment