Using secondary datasources in Grails 3

Something changed in Grails 3 and how datasources are configured. This post will explain what you need to do..

Mike Hostetler

Something changed in Grails 3 and how datasources are configured.

If you have datasources defined like this:

dataSources:
       dataSource:
           pooled: true
           jmxExport: true
           driverClassName: org.h2.Driver
           username: sa
           password:
           dbCreate: create-drop
           url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
       secondary:
           pooled: true
           jmxExport: true
           driverClassName: org.h2.Driver
           username: sa
           password:
           dbCreate: create-drop
           url: jdbc:h2:mem:devDb2;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE

You can use the “other datasource” (secondary) in a Grails domain class very simply:

class Book {  

       String title  

       static constraints = {
       }  

       static mapping = {
           datasource 'secondary'
       }
   }

And you can use the dataSource object by name in a Grails service like this:

class MyService {  

      def dataSource
   .....
   }

So you would think that the following would work:

class MyService {  

      def secondary
   .....
   }

but it doesn’t… Grails doesn’t know how to wire that secondary datasource so it’s null.

Instead, you have to put it in the resources.groovy or use Spring’s @Autowired on it like so:

class BookSqlSecondaryService {  

      @Autowired
      @Qualifier('dataSource_secondary')
      def secondary
   }

The documentation will be updated in Grails 3.2 but it’s still the case in Grails 3.0.x and Grails 3.1.x.

Share this Post

Related Blog Posts

JVM

Unit Testing URI-Based Grails Filters

March 1st, 2016

A workaround for the inability to mock URI-based filters in Grails.

Igor Shults
JVM

An Introduction to Kotlin

February 23rd, 2016

An overview of the Kotlin programming language which keeps the good parts of Java while reducing boilerplate to promote better Object-Oriented code.

Mike Plummer
JVM

Mapping JPA entities to external REST resources in spring-data-rest

February 18th, 2016

This Spring Boot example shows how you can map JPA entities to REST endpoints and embed them in the HATEOAS output via spring-data-rest and annotations.

Object Partners

About the author

Mike Hostetler

Sr. Consultant

Mike has almost 20 years of experience in technology. He started in networking and Unix administration, and grew into technical support and QA testing. But he has always done some development on the side and decided a few years ago to pursue it full-time. His history of working with users gives Mike a unique perspective on writing software.