Search code examples
javahibernatehibernate-annotations

Hibernate aggregating


Is it possible to get as a result from hibernate directly this...

List<Map<Sth, List<SthLog> list;

when classes are mapped in such a way (not bidirectional)?:

@Entity
public class SthLog {

        @ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
    private Sth sth; }

I know that this maybe seems to be a silly question, because normally you can add bidirectional mapping, but in this case I can change entities definition and I wonder if I can get required structure directly from hibernate.


Solution

  • Just don't expect Hibernate to do everything for you. Transforming a List into a Map (or a Guava Multimap, which is easier and more appropriate here) is a matter of 3 lines of codes:

    // get all the SthLog with their sth
    List<SthLog> list = 
        session.createQuery("select s from SthLog s inner join fetch s.sth").list();
    // index them by their sth
    ListMultimap<Sth, SthLog> result = ArrayListMultimap.create();
    for (SthLog sthLog : list) {
        result.put(sthLog.getSth(), sthLog);
    }