Ted Vinke's Blog

Java, Groovy and stuff



Hibernate class metadata through Spring

On a Spring-Hibernate project I’m working on we use a custom way of filling and clearing specific database tables in unit tests. Yes, something like DbUnit but ofcourse completely hand-made, tailored to our situation 🙂 In a TestNG testcase we do something like this:

public void setUp() {
	DatabaseFiller.fillTable("UserAccounts", "useraccounts.txt");

public void tearDown() {

It bugged a little bit, that in this testcase e.g. we’re testing operations on the User entity (e.g. User.class) – which for database specific reasons was mapped to a “UserAccounts” table – but we still have to find the actual table name for ourselves. There are many reasons to map explicitly to a certain table name: prevent database reserved keywords (“user” is often reserved), enforce a naming convention (“tbl_user”), etc. If no specifics have been set for Hibernate it will take its own naming convention, else one could indicate the desired name through the javax.persistence.Table annotation – if using JPA. Continue reading “Hibernate class metadata through Spring”

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 {

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

    def sessionFactory

Blog at

Up ↑