Hi guys,
I was working with a sample Grails application and I needed a way to fetch the name of the table using a domain object. I searched and found a solution.
Get table associated with a domain programmatically:
For example:-
1 2 3 4 5 6 7 |
[php] class Jft { static mapping = { table 'jft_table' } } [/php] |
If table name if defined explicitly we can simply import this:-
1 2 3 |
[php] org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainBinder [/php] |
and use:-
1 2 3 |
[php] def tableName = GrailsDomainBinder.getMapping(Jft).table.name [/php] |
and if we have an instance of the Jft class we can use this:-
1 2 3 |
[php] def tableName = GrailsDomainBinder.getMapping(jftObject.class).table.name [/php] |
But the above can only be used if table name is defined explicitly in mapping.
If we want to get a table name even if it is not specified in mapping closure, we can fetch it using SessionFactory:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
[php] import org.hibernate.metadata.ClassMetadata import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainBinder import org.codehaus.groovy.grails.commons.ApplicationHolder Class domainClass = Class.forName("com.jft.domain.Employee", true, Thread.currentThread().getContextClassLoader()) String tableName def sessionFactory = ApplicationHolder.application.mainContext.getBean("sessionFactory") ClassMetadata hibernateMetaClass = sessionFactory.getClassMetadata(domainClass) tableName = hibernateMetaClass.getTableName() println "Table name is: " + tableName [/php] |
ApplicationHolder is a static singleton holder and is used to return GrailsApplication instance.
ClassMetadata is used to extract entity class metadata(data about data). Documentation
Hope it helps 🙂
Recent Comments