【问题标题】:Resolve SQL dialect using hibernate使用hibernate解析SQL方言
【发布时间】:2012-01-05 12:39:49
【问题描述】:

我负责将现有项目从 Oracle 移植到 MSSQL,但同时保持两者的功能。 Legacy 项目使用 Hibernate 3.x,但包含一些复杂的本地查询。 所以我想知道使用的是哪种方言。

【问题讨论】:

    标签: hibernate


    【解决方案1】:

    我终于找到了方法 - 但它是特定于 Hibernate 的。

    //take from current EntityManager current DB Session
    Session session = (Session) em.getDelegate();
    //Hibernate's SessionFactoryImpl has property 'getDialect', to
    //access this I'm using property accessor:
    Object dialect = 
           org.apache.commons.beanutils.PropertyUtils.getProperty(
              session.getSessionFactory(), "dialect");
    //now this object can be casted to readable string:
    if( dialect.toString().contains("Oracle")){
       ....
    

    【讨论】:

      【解决方案2】:

      另一种短一点的方式:

      private @Autowired SessionFactory sessionFactory;
      
      public Dialect getDialecT(){
          SessionFactoryImplementor sessionFactoryImpl = (SessionFactoryImplementor) sessionFactory;      
          return sessionFactoryImpl.getDialect();     
      }
      

      【讨论】:

        【解决方案3】:

        这是针对 Hibernate 的另一种解决方案。它仍然很丑,因为它涉及向下转换,但它不使用反射:

        Session session = (Session) entityManager.getDelegate();
        SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) session.getSessionFactory();
        Dialect dialect = sessionFactory.getDialect();
        if (dialect.toString().contains("Oracle")) { ... }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-08-27
          • 2016-06-12
          • 1970-01-01
          • 1970-01-01
          • 2017-04-05
          • 2019-08-07
          • 2018-03-26
          • 2019-01-26
          相关资源
          最近更新 更多