Gana
Gana

Reputation: 492

Reading Datasource metadata using apache metamodel

I would like to read metadata of the datasource. Be it a Database or Files. The requirement is to display the set of available tables and columns of each table. I also would like to know the details of foreign keys, etc. I know this should be possible using JDBC API. But i would like to know if Apache Metamodel supports this in an abstracted way which can be used for all types of datasources.

Great, if you can share any examples.

...... Ram

Upvotes: 0

Views: 499

Answers (1)

TomaszGuzialek
TomaszGuzialek

Reputation: 871

Schemas, tables and columns can be explored in Apache Metamodel. The DataContext has a schema called "information_schema" that you can see metadata about the data context. Find this snippet for an example:

    // Prepare a data context based on plain old Java objects
    List<TableDataProvider<?>> tableDataProviders = new ArrayList<TableDataProvider<?>>();
    SimpleTableDef tableDef1 = new SimpleTableDef("snippetTableName1", new String[] {"id", "name"});
    tableDataProviders.add(new ArrayTableDataProvider(tableDef1,
            new ArrayList<Object[]>()));
    PojoDataContext dataContext = new PojoDataContext("snippetSchemaName", tableDataProviders);

    // Prints a schema tree
    for (Schema schema : dataContext.getSchemas()) {
        System.out.println("Schema: " + schema.getName());
        for (Table table : schema.getTables()) {
            System.out.println("\t Table: " + table.getName());
            for (Column column : table.getColumns()) {
                System.out.println("\t\t Column: " + column.getName() + " of type: " + column.getType());
            }
        }
    }

This should print:

Schema: information_schema
 Table: tables
     Column: name of type: VARCHAR
     Column: type of type: VARCHAR
     Column: num_columns of type: INTEGER
     Column: remarks of type: VARCHAR
 Table: columns
     Column: name of type: VARCHAR
     Column: type of type: VARCHAR
     Column: native_type of type: VARCHAR
     Column: size of type: INTEGER
     Column: nullable of type: BOOLEAN
     Column: indexed of type: BOOLEAN
     Column: table of type: VARCHAR
     Column: remarks of type: VARCHAR
 Table: relationships
     Column: primary_table of type: VARCHAR
     Column: primary_column of type: VARCHAR
     Column: foreign_table of type: VARCHAR
     Column: foreign_column of type: VARCHAR
Schema: snippetSchemaName
     Table: snippetTableName1
         Column: id of type: VARCHAR
         Column: name of type: VARCHAR

Upvotes: 1

Related Questions