grails domain mapping « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ grails domain mapping ’

Grails: Get table name mapped to a domain

Posted by roni on August 19th, 2011

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
Ron
roni[at]intellligrape[dot]com

  • Share/Bookmark
Posted in Grails

How to Map database table without id with grails domain

Posted by Uday Pratap Singh on September 7th, 2010

Recently I got a query regarding mapping a database table which do not have any id and version. For example the table have two varchar fields username and password nothing more than that.
Although it was something strange for me that table doesn’t have the id field. The good thing is that the username is a primary key in the table and this is not auto incremented user want to create it by his own method.

The good thing about grails is, in most of the cases you get your answer in the docs http://grails.org/doc/latest/ . So in this case we just need to change the id field in grails domain like this

class Test {
    String username
    String password
 
    static mapping = {
        id name: 'username'
        version false
        id generator: 'assigned'
    }
    static constraints = {
        username(nullable: true)
    }
}

and we are done :) .
Hope it helps
## Uday Pratap Singh ##
uday@intelligrape.com

http://www.IntelliGrape.com/
http://in.linkedin.com/in/meudaypratap

  • Share/Bookmark
Posted in Database, GORM, Grails