3

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.

Mariusz
  • 1,907
  • 3
  • 24
  • 39

2 Answers2

3

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
}
Community
  • 1
  • 1
Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
  • @lexicore My first thought was also dialects, but then jdbc came to my mind. Hopefully this works, as I haven't tried it myself. – Predrag Maric Nov 26 '14 at 09:24
0

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.

lexicore
  • 42,748
  • 17
  • 132
  • 221