Getting the database column name from the property of a grails domain
I'm mapping a bunch of legacy tables with my domain objects. Is there a way to find the database column name of a property in a Domain class (or vice versa)? For example:
class Person {
String firstName
.
.
.
}
is there a way to use firstName to get back the string "FIRST_NAME" or "first_name"? I've tried to use
GrailsDomainBinder.getMapping(Person).columns
but that only gives me the id column for some reason. Thanks!
Okay, I think this is what you're 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 retrieve the domain data with the following command:
def result = GrailsDomainBinder.getMapping(Company).columns
println result['logoUrl'].column //prints 'lo_go_url'
You could also print out all the column names with the following closure:
result.each{ key, val -> // The key is the attribute name in the class (i.e. 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!
I just tossed this code together, so please don't beat me up on style. :-)
Try dropping it into a test action method in your 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}"
}
}
}
}
I was able to get it in a bit hackish way :
def dbColumnNames = sessionFactory.getClassMetadata(clazz).propertyMapping.getColumnNames(fieldName)
this returns an array of string in which the first element should be the DB column name of the field.
works under with Grails 2.3.6
链接地址: http://www.djcxy.com/p/37096.html下一篇: 从grails域的属性获取数据库列名称