Adding a Projection to a List in Hibernate

前端 未结 3 490
深忆病人
深忆病人 2021-01-21 17:39

I have a @Entity called Order in this I have a field or a member variable called orderEmails as show below.

@Entity
@Table(name = \"order\")
public class Order {         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-21 18:14

    it's not possible like you expect. Hibernate has to group the records on the root entity which it only does for complete entities.

    • you could load the complete entity eager fetching the emails and transform it in memory later.
    • you fetch the root entity records duplicated for each email address and group them together in memory

    Update:

    List results = session.createCriteria(Order.class)
        .joinAlias("orderEmails", "email")
        .setProjection(Projections.projectionList()
            .add(Projections.property("id").as("id"))
            .add(Projections.property("email.EmailAddress").as("email")))
        .list();
    
    Map> groups = new Hashmap>();
    for (Object[] items : results)
    {
        if (groups.containsKey((long)items[0]))
            groups.get((long)items[0]).add((String)items[1]);
        else
            groups.add((long)items[0], new List().add((String)items[1]));
    }
    
    return groups;
    

    instead of the map one could also have dtos or something like that.

提交回复
热议问题