getting hibernate default schema name programmatically from session factory?
This will do the trick:
SessionFactoryImplementor sfi = (SessionFactoryImplementor) getSessionFactory();
Settings settings = sfi.getSettings();
ConnectionProvider connectionProvider = settings.getConnectionProvider();
try {
Connection connection = connectionProvider.getConnection();
DatabaseMetaData databaseMetaData = connection.getMetaData();
String url = databaseMetaData.getURL();
//substring the string to what you want
System.out.println(url);
} catch (SQLException e) {
//throw something
}
I just found out that hibernate has {h-schema} replacement that can be used in native sql queries. So this does the job cleanly when you are connected to a one schema in oracle database and want to execute queries against different schemas. Example would be:
select * from {h-schema}table_name
This ways instead of doing a manual replaceAll
in a query, hibernate will take care of everything given that each session factory is configured with "hibernate.default_schema"
property.
I had problems with John's solution to use {h-schema} when using the Criteria api's Restrictions.sqlRestriction(...) (probably because this substitution happens within the separate HQL api). Similar to Michael's solution, I used:
SessionFactoryImplementor sfi = (SessionFactoryImplementor)sessionFactory;
String name = sfi.getSettings().getDefaultSchemaName();