Monday, January 3, 2011

Dynamic query in liferay 5.2.+

Liferay provides “LocalServiceUtil” to interact with database, we can do the common and basic functionality using these LocalServiceUtil classes. However sometimes we may need to run complex quires beside the common service like filtering out from result list or directly getting the data by certain criteria etc. Liferay provides several factory classes in this case to make our life easier, listed bellow:

DynamicQueryFactoryUtil
OrderFactoryUtil
ProjectionFactoryUtil
PropertyFactoryUtil
RestrictionsFactoryUtil

Here I will provide a example on how to use DynamicqueryFactoryUtil to make dynamic query.

ClassLoader cl = PortalClassLoaderUtil.getClassLoader();
DynamicQuery dqi = DynamicQueryFactoryUtil.forClass(
AnnouncementsEntry.class, cl);

Criterion crit = PropertyFactoryUtil.forName("title").eq(title);
dqi.add(crit);

crit = PropertyFactoryUtil.forName("displayDate").eq(displayDate);
dqi.add(crit);

try {
results = AnnouncementsEntryLocalServiceUtil.dynamicQuery(dqi);

} catch (SystemException e) {
e.printStackTrace();
}

classloader ensure that the implementation class can be loaded . Propertyfactoryutil may used for checking certain feature like equality, between, empty, nonempty etc ie. Projection/ restriction. Actually PropertyFactoryUtil return a Property instance that allows us to create Criterion objects and to assign them in DynamicQuery.

1 comment:

  1. Hi Ahasan ,
    I tried same way but it didn't worked for Liferay 5.2.3. Can you please guide me as i need to fetch latest Announcement entry for that specific CompanyId as i have many diffenstances created. Your help will be highly appreciated.
    I didn't got any results.

    Thanks,
    Santosh Savant

    ReplyDelete