(Quick Reference)

4 GORM Enhancer - Reference Documentation

Authors: Graeme Rocher

Version: 5.0.0.BUILD-SNAPSHOT

Table of Contents

4 GORM Enhancer

Once you have implemented the lower-level APIs you can trivially provide a GORM API to a set of Grails domain classes. For example consider the following simple domain class:

import grails.persistence.*

@Entity class Book { String title }

The following setup code can be written to enable GORM for MongoDB:

// create context
def context = new MongoMappingContext(databaseName)
context.addPersistentEntity(Book)

// create datastore def mongoDatastore = new MongoDatastore(context) mongoDatastore.afterPropertiesSet()

// enhance def enhancer = new MongoGormEnhancer(mongoDatastore, new DatastoreTransactionManager(datastore: mongoDatastore)) enhancer.enhance()

// use GORM! def books = Book.list()

They key part to enabling the usage of all the GORM methods (list(), dynamic finders etc.) is the usage of the MongoGormEnhancer. This class subclasses org.grails.datastore.gorm.GormEnhancer and provides some extensions to GORM specific to MongoDB. A subclass is not required however and if you don't require any datastore specific extensions you can just as easily use the regular GormEnhancer:

def enhancer = new GormEnhancer(mongoDatastore, new DatastoreTransactionManager(datastore: mongoDatastore))
enhancer.enhance()

4.1 GORM APIs

The GormEnhancer class defines three methods called getStaticApi, getInstanceApi and getValidationApi that return instances of GormStaticApi, GormInstanceApi and GormValidationApi respectively. If you wish to provide custom GORM functionality then you can subclass each of these and override one of the aforementioned methods to provide said functionality.

For example GORM for MongoDB does this to provide access to the underlying DBCollection:

class MongoGormStaticApi<D> extends GormStaticApi<D> {
    …
    /**
     * The actual collection that this entity maps to.
     *
     * @return The actual collection
     */
    DBCollection getCollection() {
        MongoDatastore ms = datastore
        def template = ms.getMongoTemplate(persistentEntity)

def coll = template.getCollection(ms.getCollectionName(persistentEntity)) DBCollectionPatcher.patch(coll) return coll } }

With this method in place users of GORM for MongoDB can access the underlying MongoDB API directly:

def dbo = Book.collection.findOne()

The enable usage of this API the MongoGormEnhancer extends and overrides the getStaticApi method:

class MongoGormEnhancer extends GormEnhancer {
    …
    protected <D> GormStaticApi<D> getStaticApi(Class<D> cls) {
        return new MongoGormStaticApi<D>(cls, datastore, finders)
    }   
}