Foren

Dynamic Query in FreeMarker

thumbnail
James Falkner, geändert vor 8 Jahren.

Dynamic Query in FreeMarker

Liferay Legend Beiträge: 1399 Beitrittsdatum: 17.09.10 Neueste Beiträge
Recently a colleague (*coughjamiesammonscough*) asked about doing dynamic queries from FreeMarker - the trouble is, model classes and class loaders are notoriously difficult to instantiate from FreeMarker and Velocity (moreso in FreeMarker) so we spent some time looking through Liferay's codebase and discovered a few tricks that make Dynamic Queries possible in FreeMarker, just as easily as they are in Velocity (or in Java, but who writes that? emoticon ).

Here's an example Dynamic Query in FreeMarker that returns all Users with the first name of "Test":

<#assign userClass = staticUtil["com.liferay.portal.kernel.util.ClassResolverUtil"].resolveByPortalClassLoader("com.liferay.portal.model.User") />

<#assign q = staticUtil["com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil"].forClass(userClass) />

<#assign VOID = q.add(staticUtil["com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil"].eq("firstName", "Test")) />

<ul>
&lt;#list staticUtil["com.liferay.portal.service.UserLocalServiceUtil"].dynamicQuery(q) as userObj&gt;
  <li>The user's full name: <b>${htmlUtil.escape(userObj.getFullName())}</b></li>
<!--#list-->
</ul>


Hope you find it helpful! This was tested on Liferay 6.2 CE GA4. No idea if it works on 6.1 or not!
thumbnail
David H Nebinger, geändert vor 8 Jahren.

RE: Dynamic Query in FreeMarker

Liferay Legend Beiträge: 14914 Beitrittsdatum: 02.09.06 Neueste Beiträge
Just my opinion, but if you find yourself doing complex stuff in freemarker I think you're busy trying to push the square peg into a round hole.

emoticon
thumbnail
James Falkner, geändert vor 8 Jahren.

RE: Dynamic Query in FreeMarker

Liferay Legend Beiträge: 1399 Beitrittsdatum: 17.09.10 Neueste Beiträge
David H Nebinger:
Just my opinion, but if you find yourself doing complex stuff in freemarker I think you're busy trying to push the square peg into a round hole.

emoticon


Of course, I've said this all along emoticon It doesn't replace Java or sound architectural principals, but it's good for quick prototyping without the need to deploy (and re-deploy, etc).