Tuesday, April 23, 2013

Liferay: using DynamicQuery in a velocity template.

Consider a scenario if you have 1000 records in a Dynamic Data List (DDL) record set. You need to show only 20 latest records. One ways is to bring all the records and use a loop to show the records and break when a counter is greater then 20, this will cause slowness in page as you are bringing the complete record set.

To overcome this consider if you bring only latest 20 records from database something like at most list screens in liferay where pagination is used. Below is the set of lines that will allow you to achieve this;



#set ($ddlRecordSet = $serviceLocator.findService('com.liferay.portlet.dynamicdatalists.service.DDLRecordSetLocalService'))
#set ($ddlLocalService = $serviceLocator.findService('com.liferay.portlet.dynamicdatalists.service.DDLRecordLocalService'))

#set ($recordSetId = $getterUtil.getLong($reserved_record_set_id.data, 0))
#set ($DDLrecordClass = $portal.getClass().forName("com.liferay.portlet.dynamicdatalists.model.DDLRecord"))
#set ($dqfu = $portal.getClass().forName("com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil"))
#set ($ofu = $portal.getClass().forName("com.liferay.portal.kernel.dao.orm.OrderFactoryUtil"))
#set ($rfu = $portal.getClass().forName("com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil"))
#set ($q = $dqfu.forClass($DDLrecordClass))
#set ($V = $q.add($rfu.eq("recordSetId", $getterUtil.getLong($recordSetId))))
#set ($V = $q.addOrder($ofu.desc("modifiedDate")))
#set ($records = $ddlLocalService.dynamicQuery($q,0,20))
#set ($recordTitle = $ddlRecordSet.getRecordSet($recordSetId))
#set ($title = $recordTitle.getName())

You can modify the dynamic query as per your needs to order data on different columns.