Adding a Projection to a List in Hibernate

前端 未结 3 450
深忆病人
深忆病人 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:24

    I guess hibernate does not provide such a function. To do this you will have to use database specific functions like LISTAGG from Oracle or GROUP_CONCAT from MySQL. It will group all emails (the String) into one colum, so the result would be:

    ORDER_ID     EMAILS
    1            nemo@email, dory@email, whale@email
    2            spongebob@email, squarepants@email
    

    You can use database specific functions in Hibernate with sqlProjection, so the code will look something like this:

    public List emailsByOrder(){
        Criteria c = session.createCriteria(Order.class,"order");
    
        Criteria critEmail = c.createCriteria("orderEmails", "emails");
        String listAgg = "LISTAGG({alias}.EMAIL_ADDRESS_COLUMN_NAME, ', ') WITHIN GROUP(ORDER BY {alias}.EMAIL_ADDRESS_COLUMN_NAME ASC) AS EMAILS";
        critEmail.setProjection(Projections.projectionList().add(Projections.groupProperty("order.idOrder").as("ORDER_ID"))
                                                            .add(Projections.sqlProjection(listAgg, new String[]{"EMAILS"}, new Type[]{new StringType()}))); 
        c.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    
        return (List) c.list();
    }
    

提交回复
热议问题