Search code examples
javadatabasejpaeclipselink

retrieve database schema dynamically


I want to write a backup tool for my application and have to use JAVA 1.6. Inside my application are several databases like derby, mySQL .. Further there are different database schema names.

I´m using JPA and Eclipselink.

So far I wrote a method which creates a list of all tables with a specific schema name :

    private static List<String> getTableNames(String schema, Connection connection) throws SQLException {
    final String TABLE_NAME = "TABLE_NAME";
    List<String> tableNames = new ArrayList<>();
    DatabaseMetaData dbmd = connection.getMetaData();
    ResultSet tablesRS = dbmd.getTables(null, schema, null, null);
    while (tablesRS.next()) {
        tableNames.add(tablesRS.getString(TABLE_NAME));
    }

    return tableNames;
}

This works but I don´t know how I get the actualy schema name. I thought I can get the schema through the EntityManager. But I did not find any solution. Is there a way to get the schema name of my database through the EntityManager? Is there a better way to dynamically retrieve the content of all tables which works with different databases?

Notice, that I must use Java 1.6.

I know there exists a method getSchema() inside a connection object since JAVA 1.7.


Solution

  • I just found a solution for my problem at Java Code Geek. I thought I have to use the schema to get all tables. This it not the case:

    public static ArrayList getTablesMetadata() throws SQLException {
        String table[] = { "TABLE" };
        ResultSet rs = null;
        ArrayList tables = null;
        // receive the Type of the object in a String array.
        rs = metadata.getTables(null, null, null, table);
        tables = new ArrayList();
        while (rs.next()) {
            tables.add(rs.getString("TABLE_NAME"));
        }
        return tables;
    }