Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 696
Daud Avatar asked Aug 04 '12 10:08

Daud


People also ask

Is JPQL and HQL same?

The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.

Is JPQL HQL database independent?

Hibernate Query Language (HQL) Instead of table name, we use class name in HQL. So it is database independent query language.

Can we use select * in HQL?

Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but properties like table and column names are case sensitive in HQL.

How do I run a HQL query?

openSession(); Transaction tx = session. beginTransaction(); Query query = session. createQuery("select and so on.."); // set parameter values, e.g. // query. setString("name", "Matthias"); List result = query.


1 Answers

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(); 
like image 135
dimas Avatar answered Oct 01 '22 18:10

dimas