簡體   English   中英

JPA,實體管理器,選擇許多列並獲取結果列表自定義對象

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

我如何獲得自定義對象列表,如查詢下面的結果:

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

舉例:

return getEntityManager().createQuery("SELECT p.category.id, count(p.id) FROM Product p left join p.category c WHERE p.seller.id=:id GROUP BY c.id").setParameter("id", id).getResultList();

我需要一張類別ID和類別中的產品數量的地圖。

不幸的是,JPA沒有提供在Map檢索結果的標准方法。 但是,通過遍歷結果列表手動構建地圖非常簡單:

TypedQuery<Object[]> q = getEntityManager().createQuery(
    "SELECT c.id, count(p.id) " +
    "FROM Product p LEFT JOIN p.category c " +
    "WHERE p.seller.id = :id " +
    "GROUP BY c.id", Object[].class).setParameter("id", id);

List<Object[]> resultList = q.getResultList();
Map<String, Long> resultMap = new HashMap<String, Long>(resultList.size());
for (Object[] result : resultList)
  resultMap.put((String)result[0], (Long)result[1]);

假設你正在使用hibernate(標記),可以嘗試下面的HQL查詢,我還沒有測試過。

SELECT new map(p.category.id as category_id, count(p.id) as id_count) FROM Product p left join p.category c WHERE p.seller.id=:id GROUP BY c.id

使用JPA 2.0和EclipseLink impl

對於第一個問題:自定義對象列表(沒有表對象):

回答:創建自定義模型並使用@Entity和@Id

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

創建查詢並執行

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();

第二個:如何在地圖上閱讀響應

回答:使用QueryHints和ResultTypes(這是@DannyMo答案的一個變體)

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

我希望這有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM