JPA JPQL加入列查询

时间:2015-04-07 16:31:57

标签: jpa

我有一个带有连接选项的JPQL查询,我正在使用amcharts作为我的应用程序的统计部分。我能够获得查询的结果列表,但我无法弄清楚这个结果列表的列名来实现amcharts。

    public List<Object[]> StatsByCategorie() {
    Query query = em.createQuery("SELECT d.libelleCategorie AS libelle,            COUNT(t) AS stat FROM Categorie d JOIN d.listActualite t GROUP BY     d.libelleCategorie");

    @SuppressWarnings("unchecked")
    List<Object[]> results = query.getResultList();

        for (int i = 0; i < results.size(); i++) {
            Object[] arr = results.get(i);
            for (int j = 0; j < arr.length; j++) {
                System.out.print(arr[j] + " ");
            }
            System.out.println();



        }
        return results;
}

我想知道此查询的列名。

1 个答案:

答案 0 :(得分:1)

结果列表中没有列名,只有一个Object数组。

public List<Object[]> StatsByCategorie() {
Query query = em.createQuery("SELECT d.libelleCategorie AS libelle,            COUNT(t) AS stat FROM Categorie d JOIN d.listActualite t GROUP BY     d.libelleCategorie");

@SuppressWarnings("unchecked")
List<Object[]> results = query.getResultList();

    for (int i = 0; i < results.size(); i++) {
        Object[] arr = results.get(i);
        for (int j = 0; j < arr.length; j++) {
            //when j = 0, arr[j] prints 'libelle' value
            //when j = 1, arr[j] prints 'stat' value
            System.out.print(arr[j] + " ");
        }
        System.out.println();



    }
    return results;
}

要在结果中使用列名,您必须创建元组

的查询
public List<Tuple> StatsByCategorie() {
Query<Tuple> query = em.createQuery("SELECT d.libelleCategorie AS libelle, COUNT(t) AS stat FROM Categorie d JOIN d.listActualite t GROUP BY     d.libelleCategorie", Tuple.class);

@SuppressWarnings("unchecked")
List<Tuple> results = query.getResultList();

    for (int i = 0; i < results.size(); i++) {
        Tuple arr = results.get(i);
        System.out.print(arr[i].get('libelle') + " ");
        System.out.print(arr[i].get('stat') + " ");
        System.out.println();



    }
    return results;
}