Quicktip! Grails scaffolding: enums and i18n

Grails scaffolding feature is a great asset for quickly generating create/read/update/delete (CRUD) screens for your domain classes. Create an entity, create a controller and put static scaffold on top. For various types of properties within your domain class a suitable (HTML) input is used, to take the user’s input: booleans become checkboxes, associations with other domain classes become (depending on ownership and constraints) e.g. dropdowns or multi-selects, etc.

Even an enum works out of the box as one could imagine :-) This post serves as a small quicktip – primarily for me and other developers looking for these kind of things – of internationalizing scaffolded screens in general and enums in particular using  toString() and Spring’s MessageSourceResolvable.

Take the following Product with a Status:

class Product {

	enum Status {
		AVAILABLE, SOLD_OUT
	}

	String name
	Status status

	static constraints = { name blank: false, unique: true }
}

class ProductController {

	def scaffold = true
}

Opening up our /product/create url will show what you would expect.

Continue reading

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