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

Viewed 64183

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 ?

4 Answers

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

The JPA specification allows us to customize results in an object-oriented fashion.

More information you can find at this link

There is an even more elegant way

Related