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

自古美人都是妖i 提交于 2019-12-17 23:06:36

问题


In JPQL, I can retrieve entities by :

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

But, if I wish to retrieve the id and name fields (only) of the Category entity, I need something like the ResultSet object, through which I can say : rs.getString("name") and rs.getString("id"). How to do this through JPQL, without retrieving the entire entity ?

Basically, for a how to retrieve information from a query like : select c.id,c.name from Category c ?


回答1:


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<Object[]> 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<Object[]> rows = entityManager.createQuery(queryString).getResultList();



回答2:


It is not the use of the .list() function itself which makes the result a List<Object[]>. It is the specification of fields (c.id, c.name) in the HQL query. If your query is

    "select c from Category c"

Then query.list() will return a List<Category> object.




回答3:


You can also directly map to the class

public class UserData {

    private String name;
    private Date dob;
    private String password;
//setter
}



  public UserData getUserData() {
        String queryString = "select user.name as name, user.dob as dob, user.userses.password as password from UserProfile user where user.userEmailId='faiz.krm@gmail.com'";
        Query query = sessionFactory.getCurrentSession().createQuery(queryString);
        query.setResultTransformer(Transformers.aliasToBean(UserData.class));
        return query.uniqueResult();
    }


来源:https://stackoverflow.com/questions/11807698/how-to-retrieve-only-certain-fields-of-an-entity-in-jpql-or-hql-what-is-the-equ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!