Grails Groovy

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

4 comments

  1. Thanks for this hint.

    Unfortunately you forgot to add the part, where the Connection c is obtained from the session or session factory.

    Like

  2. Wolfgang, you’re right – I forgot a part. I updated the post, thanks!

    Like

  3. At first I had multiple update statements which independently were allowed to fail – hence an outer and an inner try-block 🙂

    Like

Comments are closed.