Grails Anti-Pattern: Locally Optimized Dynamic Finders Everywhere

The context

Grails makes it very easy to persist and find stuff using domain classes. It uses GORM (Grails’ Object Relational Mapping) under the hood, which by default uses Hibernate to map domain classes to tables in a database. Powerful stuff and makes it easy to get up ‘n running very fast!

Creating a new application, following so-called “best practices” from blogs like these 🙂 and the ‘idiomatic Grails-way’ described in the docs and in tutorials work in the beginning, but there’s always a tipping point — where the application has grown a reasonable size — where one should start following a different, maybe less-Grailsey, strategy.

So what can go wrong by using dynamic finders on a domain class?

Continue reading “Grails Anti-Pattern: Locally Optimized Dynamic Finders Everywhere”

Grails GORM – You Know SQL. You Know Queries. Here’s GORM.

Today I gave a presentation about Grails Object Relational Mapping (GORM) and HQL for the teams.

Everybody is pretty SQL-minded and I wanted to show them what — instead of resorting to native SQL in Grails applications right away — GORM and Hibernate can do for them, not just from getting the same queries as your own hand-crafted SQL but also showing them that readability and testability should also be first-class citizens.

View it on SlideShare or embedded below:

GORM and Hibernate’s session factory

Peter Ledbrook wrote an excellent introduction article about Grails ORM a.k.a. GORM in which the importance of Hibernate and the usage of sessions are highlighted. A quote:

Hibernate is a session-based ORM framework.

A session is retrieved from Hibernate’s SessionFactory (org.hibernate.SessionFactory) which implements a design pattern that ensures that only one instance of the session is used per thread. GORM uses this factory to get the session – and so should you if you ever need the true power of executing raw SQL in your Grails application!

An example of executing SQL yourself:

 	String sql = "some update SQL"
	Session session = sessionFactory.openSession()
 	Connection c = session.connection()
	try {
		try {
			Statement s = c.createStatement()
			s.executeUpdate sql
		}
		catch (all e) {
			log.warn "Error executing statement $sql ($e)"
		}
	}
	finally {
		session.close()
		c.close()
	}

Essential is to have the session factory auto-injected into your class, by putting the following somewhere on top:

    def sessionFactory