Grails: Getting the Data Source in a normal groovy class

十年热恋 提交于 2019-12-04 21:02:56

问题


How can I get access to the data source from within a normal groovy class? Injection doesn't work like it does with services.

The reason for this is that I need to do some manual database calls (ie: SQL statements using the groovy.sql.Sql class) from the groovy class since I'm working with a legacy database.


回答1:


dataSource is a bean which gets auto injected in services when used. All beans are auto wired in grails artifacts (controllers, services etc) by default. In your case you are using a POGO and I suppose it would be inside src/groovy.

You can inject the dataSource bean explicitly to POGO class by making it a bean by itself

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

//MyPogo.groovy
MyPogo {
    def dataSource
    ....
}

This is an expensive operation. If you already are accessing applicationContext or grailsApplication in POGO then you need not create a bean as mentioned above.

dataSource bean can be directly fetched 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 are invoking the POGO class methods from a grails artifact then use below approach than all of the above approaches. For example:

//service class
class MyService {
   def dataSource //autowired

   def serviceMethod(){
       MyPogo pogo = new MyPogo()
       pogo.dataSource = dataSource //set dataSource in POGO
   }
}



回答2:


Simple solution to do manual database calls:

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]

}


来源:https://stackoverflow.com/questions/21491074/grails-getting-the-data-source-in-a-normal-groovy-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!