Working with Rails

Recommend Brian on Working With Rails


Powered

Using GORM to Boost Legacy Spring Applications

Posted by Joseph Nusairat Wed, 09 Sep 2009 00:36:00 GMT

Using GORM with your Spring application can increase the productivity and readability of your code

Groovy and Grails has stormed the Java world as the new way to create reliable Web 2.0 applications in a concise and fast manner. The ability to go from the start of a project to the end, especially for a smaller demo, is exponentially faster. This is due to the many features of Grails. Out of the box applications are easier to build, create, test, and deploy because of the convention over configuration methodology. In addition Grails is written in Groovy, a dynamic language that can run on the JVM and interact as if they were Java classes. Groovy gives the power to write dynamic code with power and features that are normally unavailable in Java. Possibly the best example of this power in Groovy and Grails is the creation of the Grails Object Relational Mapper (GORM).

However, we can’t all just go to our managers and say “Hey, let’s rewrite this entire application in Grails”. We would more than likely get laughed out the door. At many companies it also isn’t feasible to ask for an entire framework shift. However, most of us can request “small changes”, especially if they help save time.

With Spring 2.0 and above we can create Spring beans out of Groovy objects. This gives us a nice ability to use Groovy nomenclature in our Spring code (e.g. the Meta Object Programming (MOP), cleaner syntax, etc). However, what we do not get with straight Groovy is a better way to interact with the database. For that we need the power of GORM. With Grails 1.1 that has become significantly easier.

Why Do I Want To Use GORM?

You may be familiar with Hibernate and wonder why you should bother with GORM. Hibernate is a GREAT ORM, and the framework has been developed steadily since its inception. While Spring’s wrapping of Hibernate has made it easier to interact with the database, it is still missing the readability and ease of use that most modern developers want. The following example demonstrates how GORM brings simplicity to Hibernate code. (Please note that although GORM derives from Hibernate any mention of Hibernate here will specifically be in reference to the pure Java Hibernate form.)

This example starts by performing a simple query to retrieve items from the Todo table in the database where name and description matched some given text. When using Spring’s Hibernate Template, the code would look something like this:

public List find(final String name, final String desc) {
final String hqlQuery =         
    "select t from Todo t where t.name = :name and t.description = :desc";
    return (List) getHibernateTemplate().execute(new HibernateCallback() {
    public Object doInHibernate(Session session) throws HibernateException {
        Query query = session.createQuery(hqlQuery);      
        query.setString("name", name);
        query.setString("desc", desc);
        return query.list();
    }
});    
}

Listing NUS-1

While this code does the job, something more readable would not only make it easier for everyone to understand, but would also cut down on time and errors.

Now if we were using Java Persistence API (JPA) supported queries we could make the code in Listing NUS-1 a bit simpler as shown in Listing NUS-2.

@PersistenceContext
EntityManager manager;

public List find(final String name, final String desc) {
    final String hqlQuery =         
        "select t from Todo t \
        where t.name = :name and t.decscription = :desc";
    return manager.createQuery(hqlQuery)
        .setParameter(“name”, name)
        .setParameter(“desc”, desc)
        .returnResultList();
}

Listing NUS-2

This is more concise and fairly readable, but several queries in a row would require repeating the same block of code many times with slight alterations and would increase our time and effort to do so. You may be asking yourself what is the problem with this? After all I am sure many of you have witten similar or even more verbose code before. The problem lies in the fact that code should be easily readable. As good developers we want to concern ourselves with the business logic, using the write tools. We shouldn’t have to spend too much of our time deciphering easy parts of the code, and queries to the database are often just that. Using GORM helps us to solve that problem, and here’s how.

Let’s take what that code is doing and write it in English. The code is wanting to query the Todo table to find all by name and description. Well how do we write that out? How about this:

Todo.findAllByNameAndDesc(name, desc)
That is simple, concise, and in GORM that line is actual code. This begins to show the ease of using GORM over Hibernate and we will expand on that concept when using Criteria queries later. But first, let’s see how to use GORM in our Spring application. ### Injecting GORM The interesting thing about writing an article on Using GORM with Spring is that there is barely enough setup required to fill a blog entry, let alone an entire article. In fact, you could almost Twitter the entire extra XML needed; however, for the purpose of learning we are going to go into a bit more detail. We will show not only how to set up GORM in Spring but also various options when using Spring. This will require configuring the Spring beans, installing the right JARs, and, most importantly, understanding the various ways to use GORM in your application. ### Configuring the Spring Beans We are going to go over in this section the necessary modifications to the spring files needed for using GORM with Spring. The modifications here will be to your bean configurations and are independent of whether you are using Spring in web environment or a standalone application. That being said of course if you were to be using Spring in a web environment no modifications are needed for the web specific files (like web.xml) The first thing to do is to add an XML namespace to your bean configuration. This one is specifically for GORM: xmlns:gorm="http://grails.org/schema/gorm" Once the namespace is set you will be able to use the GORM Session Factory instead of the Hibernate Session Factory. Listing NUS-3 is an example of the GORM bean definition that would go into your bean definition file..
 
     
        
          
      
      
 

Listing NUS-3

Luckily, this listing isn't too complicated. Often times with Spring beans one has to define the classes being used; however, with the use of XML namespaces that is not necessary Spring is aware based on the namespace used With that being said Listing NUS-3 serves the same purpose as your standard Hibernate definitions usually do in Spring and that is to define the Session Factory. In fact, most of the items defined will be similar to Hibernate Session Factory listings.

Line 1 is the name space reference to the GORM Session Factory, which is fairly standard stuff. The rest really is general Hibernate type configurations that are specific to GORM. Line 2 is used to specify where your domain objects exist. Remember, with Hibernate you have to define your domain objects. There are basically two ways to do this: one is to define a directory full of hibernate XML mapping files, the other is to specify a directory of domain objects. Line 3, data-source-ref, references a data source that you have defined in Spring. This can be a Java Naming and Directory Interface (JNDI) data source, in memory data source or a more database specific data source. Line 4, message-source-ref, is specific to GORM itself. GORM allows one to define validation constraints in its domain, these constraints then print out messages via a message resource bundle. In Grails this message resource bundle is a predefined name and area, with GORM you will have to specify that item yourself. In GORM these validators are in a specific place with a specific name, but with Spring one can customize the location and name of this resource bundle. On line 5 we start to define the Hibernate properties. If you were using Grails these items would be specified inside your DataSource.groovy file and if you were using JPA would be in the persistence.xml file.

JAR Files Needed

In addition to defining the GORM Session Factory we will also need a few of the Grails JAR files to make this work. Only three jars from Grails are needed and can be included either manually or via your Ivy/Maven configurations:

  • grails-bootstrap 1.1
  • grails-gorm 1.1
  • grails-web 1.1
Read more...

Posted in , , ,  | Tags , , , , ,  | no comments

Tags

agile drools gorm Grails Groovy Java orm Rails Ruby Security spring

Categories

Archives

Syndicate

Twitter