Grails: Get table name mapped to a domain « Intelligrape Groovy & Grails Blogs

Grails: Get table name mapped to a domain

Posted by

Hi guys,

Recently while working on a project, I needed to get the table names associated with a particular domain as I needed to perform complex join operations on a particular table. The database that my team was working on was a legacy database. The domains that were created were mapped to particular tables to provide backward compatibility with the existing system’s database and, hence the table names were specified in the mapping closure. Now I needed a way to get the names of the tables that were associated with a particular domain.

The SessionFactoryProxy can be directly used to get the table name associated with the domain. So the code is as follows:

import org.hibernate.metadata.ClassMetadata
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainBinder
import org.codehaus.groovy.grails.commons.ApplicationHolder

Class clazz = Class.forName("com.intelligrape.domain.Album", true, Thread.currentThread().getContextClassLoader())

String mappedTable 

def sessionFactory = ApplicationHolder.application.mainContext.getBean("sessionFactory")
ClassMetadata hibernateMetaClass = sessionFactory.getClassMetadata(clazz)
mappedTable = hibernateMetaClass.getTableName()

println "Mapped table name: " + mappedTable

Now the above modified code returns the table name associated with a domain.

Cheers
Roni C Thomas
roni[at]intelligrape[dot]com
@ronicthomas

This entry was posted on August 19th, 2011 at 12:53 am and is filed under Grails . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply