使用Hibernate解析SQL方言

bmp9r5qi  于 2022-11-24  发布在  其他
关注(0)|答案(4)|浏览(129)

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

trnvg8h3

trnvg8h31#

最后我找到了方法--但它是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")){
   ....
nimxete2

nimxete22#

另一条路稍微短一点:

private @Autowired SessionFactory sessionFactory;

public Dialect getDialecT(){
    SessionFactoryImplementor sessionFactoryImpl = (SessionFactoryImplementor) sessionFactory;      
    return sessionFactoryImpl.getDialect();     
}
jvlzgdj9

jvlzgdj93#

下面是另一个针对Hibernate的解决方案。它仍然很难看,因为它涉及到向下转换,但它没有使用反射:

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

zi8p0yeb4#

服务器升级后,遗留java系统代码停止工作,并开始返回错误消息“java.lang.NoSuchMethodException:类'class org. hib.internal. SessionFactoryImpl'“上的属性'dialect'未知。因此,为了更正该问题并将可能的影响降到最低,进行了如下调整:

之前:

Session session = (Session) entityManager.getDelegate();
    SessionFactory factory = session.getSessionFactory();
    Object dialect = null;
    try {
        dialect = PropertyUtils.getProperty(factory, "dialect");
    } catch (Exception e) {
        log.error("Error to get dialetic from entity manager", e);
    }

之后:

Session session = (Session) entityManager.getDelegate();
    SessionFactory factory = session.getSessionFactory();
    Object dialect = null;
    try {
        dialect = PropertyUtils.getProperty(factory, "dialect");
    } catch (Exception e1) {
        log.error("Error to get dialetic from entity manager", e1);
        try {
            SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) session.getSessionFactory();
            dialect = sessionFactory.getDialect();
        } catch (Exception e2) {
            log.error("Error to get dialetic from entity manager", e2);
        }
    }

注意:更新jboss/wildfly后开始出现错误。

相关问题