JPA, Entity manager, select many columns and get result list custom objects

前端 未结 3 925
名媛妹妹
名媛妹妹 2020-12-13 11:00

How I can get list of custom objects, like results below query:

SELECT p.category.id, count(p.id) FROM Product p left join p.category c WHERE p.seller.id=:id         


        
3条回答
  •  北海茫月
    2020-12-13 11:25

    Using JPA 2.0 and EclipseLink impl

    For the first question: list of custom objects(no table objects):

    answer: create a custom model and use the @Entity and @Id

    @Entity
    public class QueryModelDTO implements Serializable{ 
        @Id
        private Integer categoryId;
        private int count;
        ---gets and sets
    }
    

    create the query and execute

    QueryModelDTO qm = (QueryModelDTO) em.createQuery(
                    "SELECT p.category.id as categoryId, count(p.id) as count FROM Product p
                    left join p.category c WHERE p.seller.id=:id 
                    GROUP BY c.id",QueryModelDTO.class)
                    .setParameter("id", id).getSingleResult();
    

    For the second: how to read the response on a map

    answer: Use the QueryHints and ResultTypes (this is one variant for the @DannyMo answer)

    Query q  = em.createNativeQuery("SELECT * FROM Foo f");
    q.setHint(QueryHints.RESULT_TYPE, ResultType.Map);
    List lm = q.getResultList();
        for (Map map : lm) {
            for (Object entry : map.entrySet()) {
                Map.Entry e = (Map.Entry) entry;
                DatabaseField key = e.getKey();
                Object value = e.getValue();
                log.debug(key+"="+value);
            }            
        }
    

    I hope this helps

提交回复
热议问题