How to retrieve only certain fields of an entity in JPQL or HQL? What is the equivalent of ResultSet in JPQL or HQL?

后端 未结 4 833
名媛妹妹
名媛妹妹 2020-12-14 02:02

In JPQL, I can retrieve entities by :

query = entityManager.createQuery(\"select c from Category c\");
List categories = query.getResultList(         


        
4条回答
  •  臣服心动
    2020-12-14 02:56

    In HQL you can use list() function to get a list of Object[] array that contains result rows:

    Query query = session.createQuery("select c.id,c.name from Category c");
    List rows = query.list();
    

    in returned array 1-st element will be id, second - name.

    for (Object[] row: rows) {
        System.out.println(" ------------------- ");
        System.out.println("id: " + row[0]);
        System.out.println("name: " + row[1]);
    }
    

    If you want to use hibernate's Criteria API, you should use Projections.

    With JPA it will work the same way:

    List rows = entityManager.createQuery(queryString).getResultList();
    

提交回复
热议问题