Getting database column name from grails domain property

I map a bunch of legacy tables to my domain objects. Is there a way to find the column name of a property database in the Domain class (or vice versa)? For instance:

class Person { String firstName . . . } 

Is there a way to use firstName to return the string "FIRST_NAME" or "first_name"? I tried to use

 GrailsDomainBinder.getMapping(Person).columns 

but for some reason this gives me an id column. Thanks!

+4
source share
3 answers

Ok, I think this is what you are looking for. Given the following domain

 class Company { String name String logoUrl static mapping = { table 'people' name column: 'my_name' logoUrl column: 'lo_go_url' } } 

You can get domain data with the following command:

 def result = GrailsDomainBinder.getMapping(Company).columns println result['logoUrl'].column //prints 'lo_go_url' 

You can also print all column names with the following closure:

 result.each{ key, val -> // The key is the attribute name in the class (ie name, logoUrl) PropertyConfig prop = val // This is not needed, but I wanted to show the type being used. You could just call val.column below. println prop.column // This would print out 'my_name', 'lo_go_url' } 

Hope this helps!

+3
source

I just threw this code together, so please don't beat me in style. :-)

Try translating it into a test action method in PersonController and add my import statements and sessionFactory , as shown below:

 import org.hibernate.persister.entity.AbstractEntityPersister import org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass class PersonController { // This should get injected by Grails automatically def sessionFactory .... def myTestAction() { def domainClazz = grailsApplication.getClassForName("com.test.Person") def clazzMetadata = sessionFactory.getClassMetadata(domainClazz) def AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) clazzMetadata def grailsDomainClazz = new DefaultGrailsDomainClass(domainClazz) def grailsDomainClazzProperties = grailsDomainClazz.getProperties() grailsDomainClazzProperties.each() { println "Property Name: ${it.name}" abstractEntityPersister.getPropertyColumnNames(it.name).each() { println "DB Column: ${it}" } } } } 
+8
source

I was able to get this in a bit of a hacker way:

  def dbColumnNames = sessionFactory.getClassMetadata(clazz).propertyMapping.getColumnNames(fieldName) 

returns an array of strings in which the first element should be the column name of the database field.

works with Grails 2.3.6

+3
source

Source: https://habr.com/ru/post/1432568/


All Articles