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

Separating and securing Grails controllers

Ever wanted to have several Grails controllers automatically secured – just by name?

I had to make a subset of my Grails 1.2.2 application controllers only available to a certain group of people. A few controllers made actions on the application possible which only Administrators were allowed to do.

Acegi what?

So, I think everybody recognizes the ever so popular Acegi way (using Spring Security) of securing things with a single com.app.controller.HelloController in SecurityConfig.groovy:

security {
	active = true

	useRequestMapDomainClass = false
	requestMapString = """
		CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
		PATTERN_TYPE_APACHE_ANT

		/hello/**=ROLE_USER
		/**=IS_AUTHENTICATED_ANONYMOUSLY
	"""
}

This way a login-screen will appear when a user tries to open the HelloController on /hello since ROLE_USER is required. Well, not really high-tech yet – a basic example you could find in the Acegi plugin’s documentation as well.

More…more controllers!

Let’s introduce several other controllers next to the com.app.controller.HelloController. Notice I myself made up the package name com.app.controller – just a habit to seperate Domain classes, Controllers and Services into com.app.domain, com.app.controller and com.app.services.

Continue reading