Grails: getting a data source in a regular groovy class

How to access a data source from a regular groovy class? Injection does not work, as in maintenance.

The reason for this is that I need to make some manual database calls (i.e.: SQL statements using the groovy.sql.Sql class) from the groovy class, since I'm working with an outdated database.

+6
source share
2 answers

dataSource is a bean that is automatically inserted into services when used. All beans are automatically connected to grails artifacts (controllers, services, etc.) by default. In your case, you are using POGO, and I suppose it will be inside src/groovy .

You can explicitly introduce a dataSource bean into the POGO class by making the bean itself

 //resources.groovy beans = { myPogo(MyPogo){ dataSource = ref('dataSource') } } //MyPogo.groovy MyPogo { def dataSource .... } 

This is an expensive operation. If you are already accessing applicationContext or grailsApplication in POGO, you do not need to create a bean as described above.

dataSource bean can be directly extracted from the context as:

 //ctx being ApplicationContext def dataSource = ctx.getBean('dataSource') //or if grailsApplication is available def dataSource = grailsApplication.mainContext.getBean('dataSource') 

If you call the methods of the POGO class from the grails artifact, use the approach lower than all the above approaches. For instance:

 //service class class MyService { def dataSource //autowired def serviceMethod(){ MyPogo pogo = new MyPogo() pogo.dataSource = dataSource //set dataSource in POGO } } 
+15
source

A simple solution for manually calling a database:

 def grailsApplication def getSeqVal () { SessionFactory sessionFactory = grailsApplication.mainContext.sessionFactory def sql = "--INSERT QUERY HERE--" def query = sessionFactory.currentSession.createSQLQuery(sql); def result = query.list() return result[0] } 
0
source

All Articles