1
votes

I came to know there is a feature in JPA, which fetches only those properties of entity which we need, and it is called a projection query.

Most Datastore queries return whole entities as their results, but often an application is actually interested in only a few of the entity's properties. Projection queries allow you to query the Datastore for just those specific properties of an entity that you actually need, at lower latency and cost than retrieving the entire entity.

I am looking for an implementation of the projection queries, but it seems like there are lesser resources about this.

I have a table USER with 50 columns. I need to retrieve only 5 columns from this table as a list of entities. This is to show it in a JSF data table.

How can I achieve this with projection query? Or is there a better alternative to this?

1

1 Answers

2
votes
select u.id, u.name, u.birthDate from User u

This will return a List<Object[]>. Each Object[] in the list will contain a user ID, a user name and a user birth date.

You execute it just like a regular query:

Query q = em.createQuery(jpql);
List<Object[]> users = q.getResultList();