2009年3月19日木曜日

[Grails]How to get the database table and column names mapped to the Domain Class

How to get the database table and column names mapped to the Domain Class
  • References
    • Grails FAQ "Q: How can I flush a Hibernate session multiple times within my controller?"
      http://grails.org/FAQ
    • http://www.mail-archive.com/hibernate-devel@lists.sourceforge.net/msg06401.html

  • Description
    the way to get the database table name and column names mapped to the domain classes
    in grails application.
    The example using in controller class is as follows. Following sample is using the controller class named TestController and domain class named SampleDomainClass.
    //import 3 classes
    import org.hibernate.SessionFactory
    import org.codehaus.groovy.grails.commons.DefaultGrailsApplication
    import org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass

    class TestController {
    .....
    //variables to handle the Hibernate sessonFactory and grails application
    //please refer to the grails FAQ page if you know more details to get sessonFactory and grailsApplication objects
    def sessionFactory
    def grailsApplication

    //starting the action closure named "index"
    def index={
    .....

    //get the class object named the SampleDomainClass domain class
    def domainClass=grailsApplication.getClassForName("SampleDomainClass")
    //get hibernage meta data object
    def hibernateMetaClass=sessionFactory.getClassMetadata(domainClass)
    //get the table name mapped to the SampleDomainClass domain class
    def tableName=hibernateMetaClass.getTableName()
    println("table name=$tableName")

    //creaate a new GrailsDomainClass object for the SampleDomainClass
    def grailsDomainClass=new DefaultGrailsDomainClass(domainClass)
    //get the domain properties which keeps the domain class properties defined in Domain Class
    //grailsDomainClass.getProperties() is returned the GrailsDomainClassProperty[] objects
    //please refer to the javadoc
    //http://www.grails.org/doc/1.0.x/api/index.html?org/codehaus/groovy/grails/commons/DefaultGrailsDomainClass.html
    def domainProps=grailsDomainClass.getProperties()
    domainProps.each{prop->
    //get the property's name
    def propName=prop.getName()
    //get the database column name mapped to the domain property name
    //getPropertyColumnNames is returned the String array object
    //please refer to the hibernate javadoc
    //http://www.hibernate.org/hib_docs/v3/api/org/hibernate/persister/entity/AbstractEntityPersister.html
    def columnProps=hibernateMetaClass.getPropertyColumnNames(propName)
    if(columnProps && columnProps.length>0){
    //get the column name, which is stored into the first array
    def columnName=columnProps[0]
    println("prop=$propName, columnName=$columnName")
    }
    }
    .....
    }
    }