Grails ate my Spring persistence layer

Friday, May 7, 2010

The time-saving aspects of using Grails for web application development have been well-documented. Take, for example, an ordinary Spring/JPA application. I did a quick analysis of such an application as a concrete example of just how much code and development effort could have been saved by using the GORM features of Grails alone.

In this particular Spring application’s three repository/DAO classes, there are a total of 253 methods. Only 26 (!) of them are responsible for functionality that GORM does not provide automatically via dynamic finders or the basic CRUD functions (save/delete) on entities.

Using a slightly altered find-modify-save example from the Grails documentation, here is a comparison of the GORM and Spring code necessary to perform the same operations:

Spring:

// JPA annotations and minor details omitted for brevity
public class Person {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

public class PersonRepository {
	private EntityManager em;

	public Person findPersonById(Integer id) {
		return em.find(Person.class, id);
	}

	public Person savePerson(Person p) {
		return em.merge(p);
	}
}

PersonRepository repository; // injected by Spring
Person p = repository.findPersonById(1);
p.setName("Mark");
repository.savePerson(p);

Grails:

class Person {
    String name
}

def p = Person.get(13)
p.name = "Mark"
p.save()

Extrapolating the code savings from GORM’s dynamic finders and free save/delete methods, I was able to eliminate nearly 90% of the existing Spring persistence logic. In fact, I could have written this blog post several weeks ago… but I was too busy maintaining thousands of lines of boilerplate JPA code.:)

Here are some helpful resources to consider for integrating GORM into an existing Spring application:

Using GORM to Boost Legacy Spring Applications
Standalone GORM
Using Grails GORM standalone

Top