Wednesday 4 September 2013

Get specific column (more than 1) using Dynamic Query Liferay - ProjectionList

Introduction : I had been struggling to execute this kind of query using the Dynamic Query

Select id, name from group where id=2;
So, thought may be useful to anyone looking for it.

Solution : Use ProjectionList

Map<String,Integer> resultsMap = new HashMap< String,Integer>();
ProjectionList projectionList = ProjectionFactoryUtil.projectionList();
DynamicQuery dynaQuery = DynamicQueryFactoryUtil
.forClass(Group.class);
projectionList.add(ProjectionFactoryUtil.property("id"));
projectionList.add(ProjectionFactoryUtil.property("name"));
dynaQuery.setProjection(projectionList);
dynaQuery.add(RestrictionsFactoryUtil.eq(
"id", 2));
try {
List<Object[]> ids = (GroupLocalServiceUtil
.dynamicQuery(dynaQuery));
 for (Object[] o : ids) {
   resultsMap.put((String) o[0], ((Long) o[1]).intValue());
 }
} catch (SystemException e) {
e.printStackTrace();
}

1 comment: