pri_dev pri_dev - 1 month ago 10
Groovy Question

getting a connection object from dataSource in groovy

Our Application has a Datasource.groovy defined.
I am using it in a controller like this

import javax.sql.DataSource
class xxx {
javax.sql.DataSource dataSource

def myappsql = new Sql(dataSource)
myappsql.row(querystring) .....

}


I need to get connection object from the datasource, is this possible directly like this :

Connection conn = myappsql.getConnection()


Since this is giving me error, does it have to be a
groovy.sql.Sql
to do this call?

I am trying to avoid creating a connection object from scratch, with user, password and url string and instead reuse the one declared in datasource.

Answer

Instead of dependency-injecting the DataSource, you can dependency inject the SessionFactory

import org.hibernate.SessionFactory
import groovy.sql.Sql

class SomeService {

    static transactional = true
    SessionFactory sessionFactory

    void someMethod() {
        // Get a connection object that participates in the current transaction
        def connection = sessionFactory.currentSession.connection()

       // Use the connection to create a Sql instance
       Sql sql = new Sql(connection)
    }
}