Ultra's Brain dump What would UltraL0rd do?

Helpful Groovy + Grails tips

If you are new to Grails and have never used groovy before. I'm sure you have hit your screen at least twice today.

So here are some cool short hand tips I've learnt to make your life (and mine) much easier.

URLS

  1. http://groovy.codehaus.org/ Groovy docs
  2. http://groovy.codehaus.org/groovy-jdk/ Groovy JDK docs

Useful default Injections

Grails + Groovy comes with some useful injections you can call upon which you might not be aware of.

dataSource

dataSource you call when you wish to execute a native query. This is not preferable as you will have issues when changing DB's. But if you really need to. You do the following :

class SomeController
{
def dataSource
def someAction
{
def sql = new Sql(datasource) //If your datasource is a sql connection [datasource is setup in     DataSource.groovy]
sql.execute '''
Select st FROM someTable st
WHERE id = '1',
AND name = 'bob'
'''
}
}

Note : This will NOT be casted into your DomainClass. Use DomainClass.executeQuery for that

sessionFactory

Allows you to access Hibernates sessionFactory (and so create Hibernate queries)

class SomeController
{
def sessionFactory
def someAction
{
def hqlSession = sessionFactory.getCurrentSession() //New Hibernate Session
Query randomDataQuery = hqlSession.createQuery("SELECT st FROM someTable st ORDER BY rand()") //Randomly fetch data
randomDataQuery.setMaxResults(3)//Only get the first 3 items
def randomDataList = randomDataQuery.list() //Convert it into a list
}
}

Tips and Tricks

  1. *. - Allows you to refine a list.
    eg : randomDataList*.id will convert the list "randomDataList" to just a list of the id's
  2. .join - Allows you to join a list with a separator
    eg : randomDataList*.id.join(',') will output a string of id's separated by ','
  3. ''' or """ - Groovy's multi-line string literal. Allows you to put sql commands/text over multiple lines
    eg : '''
    this
    is
    on
    multi
    lines
    '''
  4. DomainClass.executeQuery - Will allow you to running a query against a DomainClass and retrieve a list of that type of Controller. I would personally suggest using the Hibernate Query tool. But you can use this if you want too.
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.