5

I'm responsible on porting existing project from Oracle to MSSQL, but keeping both functional. Legacy project uses Hibernate 3.x, but contains some number of sophisticated native queries. So I would like to know which dialect used.

Dewfy
  • 23,277
  • 13
  • 73
  • 121

4 Answers4

6

At last I've found the way - but it is specific for 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")){
   ....
Dewfy
  • 23,277
  • 13
  • 73
  • 121
5

Another a way a little bit shorter:

private @Autowired SessionFactory sessionFactory;

public Dialect getDialecT(){
    SessionFactoryImplementor sessionFactoryImpl = (SessionFactoryImplementor) sessionFactory;      
    return sessionFactoryImpl.getDialect();     
}
borjab
  • 11,149
  • 6
  • 71
  • 98
0

Here's another solution specific for Hibernate. It's still ugly, because it involves down casts, but it does not use reflection:

Session session = (Session) entityManager.getDelegate();
SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) session.getSessionFactory();
Dialect dialect = sessionFactory.getDialect();
if (dialect.toString().contains("Oracle")) { ... }
Stefan Haberl
  • 9,812
  • 7
  • 72
  • 81
0

After a server upgrade, a legacy java system code stopped working and started returning the error message "java.lang.NoSuchMethodException: Unknown property 'dialect' on class 'class org.hibernate.internal.SessionFactoryImpl'" . So, to correct the problem and minimize possible impacts, the adjustment made was as follows:

Before:

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

After:

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

Note: The error started to occur after updating jboss/wildfly.

Genivan
  • 171
  • 2
  • 3
  • 10