2
votes

I'm working with a grails project which uses a large 3rd party database with numerous tables and numerous fields in each table. We have taken the approach of adding these fields to our domain classes manually on an as-needed basis.

I'm at a point where I'd like systematic access to all of the fields and I'm wondering if there's a way to do this without adding them to my domain class. For example, if I know the column name, I'd like to know the datatype in the database (i.e., whether it's a string, double, int, bool, date).

I don't need programmatic access to the fields because I can interact with these tables using a REST api provided by the 3rd party vendor. I'd just like to know if I can determine what datatype they're expecting.

I found that grails has a reverse engineering plugin, but I'm not sure that's what I want because I don't want to create a domain class, I just want something like:

// this is what I work for fields I've added to the domain class
Type works = MyDomainClass.getDeclaredField("declaredFieldName").genericType
// is there a way to do this without adding it to the domain class?
Type needed = someAPI(MyDomainClass,"unDeclaredFieldName")
2

2 Answers

1
votes

Check out the hibernate tools that the reverse engineering plugin is using. Specifically, it creates a DatabaseCollector:

DatabaseCollector readDatabaseSchema(String catalog, String schema) {
    catalog = catalog ?: settings.defaultCatalogName
    schema = schema ?: settings.defaultSchemaName

    JDBCReader reader = JDBCReaderFactory.newJDBCReader(cfg.properties, settings,revengStrategy, cfg.serviceRegistry)
    DatabaseCollector dbs = new MappingsDatabaseCollector(mappings, reader.metaDataDialect)
    reader.readDatabaseSchema dbs, catalog, schema, new ReverseEngineerProgressListener()
    dbs
}
-1
votes

I think you can just use straight SQL for instance

SELECT DATA_TYPE FROM all_tab_columns WHERE table_name = 'TABLE NAME' AND column_name = 'COLUMN NAME'

And you can call SQL directly from Groovy sql http://docs.groovy-lang.org/latest/html/api/groovy/sql/Sql.html