Archive for January, 2010

Today I could once again not find a proper way to express a query needed for my current Grails project in either Hibernate HQL nor the DSL based variant of Hibernate’s Criteria API.

While it is quite simple to run native SQL Queries in Grails Project using Spring’s NamedParameterJdbcTemplate I never had to actually Map the result of a native SQL back to one of my Grails Domain Classes. After a bit of fiddling around it turned out that everything becomes quite trivial once you get ahold of the Hibernate SessionFactory that is made available by Grails for each request.

Let’s pretend we have the following Grails domain class:

?View Code GROOVY
package com.acme.domain
 
class Foo
{
  String name
}

You would execute a native SQL Query that returns a List of Foo instances like this:

?View Code GROOVY
import com.acme.domain.*
 
def sessionFactory
sessionFactory = ctx.sessionFactory  // this only necessary if your are working with the Grails console/shell
def session = sessionFactory.currentSession 
 
def query = session.createSQLQuery("select f.* from Foo where f.id = :filter)) order by f.name");
query.addEntity(com.acme.domain.Foo.class);
query.setInteger("filter", 88);
query.list()*.name;

Did you ever had to implement a menu in Grails GSP where every link element should be seperated from its predecessor by a separator character and where some of the elements can be missing when certain conditions are not met (security etc)?

The part with the optional elements can turn the separator handling into a real mess. So today I decided to end this nonsense. The result is a tiny taglib which can be integrated into every grails project. The usage is pretty self explanatory:


<mx:toolbar separator=’|'>
  <mx:item>
    <shiro:hasPermission permission=”topic:delete”>
      <g:link controller=”topic” action=”delete” id=”${topic.id}”><g:message code=”topic.delete”></g:message></g:link>
    </shiro:hasPermission>
  </mx:item>

  <mx:item>
    <shiro:hasPermission permission=”topic:lock”>
      <g:link controller=”topic” action=”lock” id=”${topic.id}”><g:message code=”topic.lock”></g:message></g:link>
    </shiro:hasPermission>
  </mx:item>
</mx:toolbar>

[More]