getting hibernate default schema name programmatically from session factory?

旧时模样 提交于 2019-12-03 16:41:01

问题


I was wondering if there is a way to get the default schema name from session factory, somehow? The reason I need to get it is because I have to use a one native SQL and I have multiple session factories for multiple schemas and a single data source. All the generated hibernate queries are being ran by a single user which has select access to other schemas.


回答1:


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.




回答2:


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();



回答3:


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
  }



回答4:


@Ryan Morlok, I can not comment on your answer due to lack of reputation. Your answer is correct, but its deprecated now. In hibernate version 5.0.1, schema name can be get using

(SessionFactoryImpl)sessionFactory).getProperties().getProperty("hibernate.default_schema")


来源:https://stackoverflow.com/questions/4832579/getting-hibernate-default-schema-name-programmatically-from-session-factory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!