Mariusz
Mariusz

Reputation: 1985

List all tables in Hibernate

I want to list all table names from database. My application has to be independent from DBMS. Different DBMS has different command to list tables, e.g:

PstgreSQL:

SELECT * FROM pg_catalog.pg_tables

MySQL:

show tables

Oracle:

SELECT DISTINCT OBJECT_NAME 
  FROM DBA_OBJECTS
 WHERE OBJECT_TYPE = 'TABLE'

I think that I should use hibernate because writing different SQL query for all DBMS is uncomfortable. There are examples in network how to list tables in hibernate, but all examples which I found list only mapped entitites. I want to list all table names regardless of hibernate entities.

Upvotes: 3

Views: 1860

Answers (2)

Predrag Maric
Predrag Maric

Reputation: 24423

This post explains how to do it using JDBC driver, which is IMHO a better approach then using hibernate for this. I'll post the code here also, for reference

Connection conn = DriverManager.getConnection("", "", "");
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
    System.out.println(rs.getString(3)); // 3rd column is table name
}

Upvotes: 3

lexicore
lexicore

Reputation: 43661

The way Hibernate makes HQL/JPQL queries and expressions cross-platform is by using dialects. There's a dialect for each of the supported database.

To the best of my knowledge, listing tables is not a part of these dialects therefore what you want is most probably not possible OOTB.

But you can write your own dialects for your target databases. So you'd have a cross-database *QL in your application and database specifics would be cleanly abstracted into dialects.

Upvotes: 0

Related Questions