3/09/2011

DynamicQuery API and ClassLoaders in Liferay

This is the third part of my dive into the world of the dynamic query api in liferay. Today we will cover the basic question "how do I get acces to the implementation class of XYZ". You need to have access to those classes because the DynamicQuery API needs to instantiate them to return the wanted results.


If you don´t have access to them, you normally get something like this:

Unable find model com.liferay.portal.model.impl.UserImpl
    java.lang.ClassNotFoundException: com.liferay.portal.model.impl.UserImpl
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
    at com.liferay.portal.dao.orm.hibernate.DynamicQueryFactoryImpl.getImplClass(DynamicQueryFactoryImpl.java:78)
    at com.liferay.portal.dao.orm.hibernate.DynamicQueryFactoryImpl.forClass(DynamicQueryFactoryImpl.java:39)
    at com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil.forClass(DynamicQueryFactoryUtil.java:29)

To prevent this exception, you need to have the right classloader and pass it to the DynamicQuery upon creation:

DynamicQuery query = DynamicQueryFactoryUtil.forClass(XYZ.class, CLASSLOADER);

There are three possibilities, and you have to choose the right one, to allow your DynamicQuery to access the implementation class:




1) The Implementation class is in your portlet:


Don´t use a special classloader - it will work out of the box.


2) The Implementation class is part of the portal (Like User, Role or Group)


Use the following:

Classloader loader = PortalClassLoaderUtil.getClassLoader());


3) The implementation class is in another portlet.


Use the following:


ClassLoader classLoader = (ClassLoader)PortletBeanLocatorUtil.locate(ClpSerializer.SERVLET_CONTEXT_NAME,"portletClassLoader");


If you like this post it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)

If you have any questions, feel free to leave a comment.