View Javadoc
1   package com.atlassian.activeobjects.confluence.hibernate;
2   
3   import com.atlassian.hibernate.PluginHibernateSessionFactory;
4   import com.atlassian.sal.api.transaction.TransactionCallback;
5   import com.atlassian.sal.api.transaction.TransactionTemplate;
6   import net.sf.hibernate.SessionFactory;
7   import net.sf.hibernate.dialect.Dialect;
8   import net.sf.hibernate.engine.SessionFactoryImplementor;
9   
10  import static com.google.common.base.Preconditions.checkNotNull;
11  
12  /**
13   * Extracts the dialect from the {@link net.sf.hibernate.SessionFactory hibernate session factory}, provided the
14   * concrete implementation, also implements {@link net.sf.hibernate.engine.SessionFactoryImplementor}.
15   */
16  public final class HibernateSessionDialectExtractor implements DialectExtractor {
17      private final PluginHibernateSessionFactory sessionFactory;
18  
19      private final TransactionTemplate transactionTemplate;
20  
21      public HibernateSessionDialectExtractor(PluginHibernateSessionFactory sessionFactory, TransactionTemplate transactionTemplate) {
22          this.sessionFactory = checkNotNull(sessionFactory);
23          this.transactionTemplate = checkNotNull(transactionTemplate);
24      }
25  
26      public Class<? extends Dialect> getDialect() {
27          // hibernate needs a transaction to create the session
28          return transactionTemplate.execute(new TransactionCallback<Class<? extends Dialect>>() {
29              @Override
30              public Class<? extends Dialect> doInTransaction() {
31                  final SessionFactory hibernateSessionFactory = sessionFactory.getSession().getSessionFactory();
32                  if (hibernateSessionFactory instanceof SessionFactoryImplementor) {
33                      return ((SessionFactoryImplementor) hibernateSessionFactory).getDialect().getClass();
34                  } else {
35                      return null;
36                  }
37              }
38          });
39      }
40  }