pri_dev pri_dev - 1 year ago 140
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
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 Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download