Spring JDBC Template in Grails Application

Posted By : Sanjay Saini | 09-Jun-2015

Spring JDBC Grails

Hi Friends ,

In this blog, i'm going to explain you how to add Spring JDBC Template support in grails application. I have need to download require jar file.

Download Jar File from this link and add it to the  build path of grails aaplication.

Following Steps needed to be follow to use Spring JDBC Template in grails Application.

Step 1: Open Resource.groovy File .

conf/spring/Resource.groovy


import org.springframework.jdbc.core.JdbcTemplate
import org.apache.commons.dbcp.BasicDataSource

beans = {

//reference  of  dataSource is defined in Grails DataSource groovy file

mainDataSourceTemplate(JdbcTemplate) {
   dataSource = ref('dataSource')        
}

// use another datasource that is different from main dataSource 

SecondaryDataSourceConfig(BasicDataSource) {
   driverClassName = "com.mysql.jdbc.Driver"
   url = "jdbc:mysql://localhost:3306/testsecondary"
   username = "uname"
   password = "pass"
}

secondaryDataSourceTemplate(JdbcTemplate) {
   dataSource = SecondaryDataSourceConfig
   }
}

Step 2 : Injecting DataSource bean in controller ,Services OR TestCases. Where you want to used.


public class TestJDBCTemplateController {

def secondaryDataSourceTemplate
def mainDataSourceTemplate 

/*suppose we have two database main database name maintest and secondary database name testsecondary .
  both contains table test with some records.test  table contains id and name columns. 
  we are getting name from both database tables using jdbc template .*/

    def testMainJdbc(){

           String sqlQuery = "SELECT name FROM test; 
           def result = mainDataSourceTemplate.queryForList(sqlQuery) 
           println "result of Query is =====>"+result.name
           println "Size of Result ========> "result.size();
         }

def testSecondaryJdbc(){

          String sqlQuery = "SELECT name FROM test; 
          def result = secondaryDataSourceTemplate.queryForList(sqlQuery) 
          println "result of Query is =====>"+result.name
          println "Size of Result ========> "result.size();
    }

def testTemplateUsingPreparedStatment(){
          String sqlQuery = "SELECT name FROM test where id = ?;
          def id = 1
          def result = secondaryDataSourceTemplate.queryForList(sqlQuery,id) 
          println "result of Query is =====>"+result.name
          println "Size of Result ========> "result.size();
} }

 

Thanks 

Please Feel Free to Contact me if you have any further Questions or Concerns.

Sanjay Saini

[email protected]

About Author

Author Image
Sanjay Saini

Sanjay has been working on web application development using frameworks like Java, groovy and grails. He loves listening to music , playing games and going out with friends in free time.

Request for Proposal

Name is required

Comment is required

Sending message..