I am using JPA in my web application and when I do not want the DB to return all of the object I do something like:
Query query = super.entityManager.createQuery("select b.id, b.buyName from Buy b where b.id in (:list)");
query.setParameter("list", buyIds);
List<Object[]> result = query.getResultList();
List<Buy> retval = new ArrayList<Buy>();
for (Object[] item : result) {
Buy buy = new Buy();
buy.setId((Long)item[0]);
buy.setBuyName((String)item[1]);
retval.add(buy);
}
return retval;
That is , querying the fields I want and then manually creating a list of the desired object and populating it.
Is this a good practice? It feels like there is a better way of doing this.
Thank you.
It’s possible to directly return a new object from the query, with just the information that you need. For instance, your query would look like this:
And the data transfer object would include only the needed fields:
When the query is run, it will return a
List<BuyDTO>