0
votes

How can I access Hibernate properties from a Grails Service?

In this instance I have to use createSQLQuery for a legacy database and need access to the hibernate.default_schema property in order to build a valid SQL statement.

class MyService {
    def sessionFactory

    def getRows() {
        def session = sessionFactory.currentSession
        session.createSQLQuery("SELECT * FROM schema.table").list()
    }
}

UPDATE

There is a quirk with Grails 2.x multiple datasources and the setting of Hibernate properties. Properties set in additional datasources are applied to the default datasource.

The properties must be set in the hibernate object instead of the datasource object:

datasource_ds2 {
    . . .
}
hibernate_ds2 {
    default_schema = "schema"
}

They can then be accessed from the hibernate config in grailsApplication:

def grailsApplication
assert grailsApplication.config.hibernate_ds2.default_schema == "schema"
1

1 Answers

3
votes

They're stored in the Config object, e.g.:

class MyService {

    def grailsApplication
    def sessionFactory

    def getRows() {

        def defaultSchema = grailsApplication.config.hibernate.default_schema
        def session = sessionFactory.currentSession
        session.createSQLQuery("SELECT * FROM ${defaultSchema}.table").list()
    }
}