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:-

class Jft {
static mapping = {
table 'jft_table'

If table name if defined explicitly we can simply import this:-


and use:-

def tableName = GrailsDomainBinder.getMapping(Jft).table.name

and if we have an instance of the Jft class we can use this:-

def tableName = GrailsDomainBinder.getMapping(jftObject.class).table.name

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:-

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

ApplicationHolder is a static singleton holder and is used to return GrailsApplication instance. Documentation

ClassMetadata is used to extract entity class metadata(data about data). Documentation

Hope it helps 🙂