【问题标题】:How to get Hibernate dialect during runtime如何在运行时获取 Hibernate 方言
【发布时间】:2014-11-28 03:18:43
【问题描述】:


在我的应用程序中,我使用 Hibernate 和 SQL Server 数据库,所以我设置了

<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect">

在我的 persistence.xml 中。

在某些情况下,我想对包含 NULL 的记录进行排序,我使用关键字 NULLS FIRST。
因为 Hibernate 中的 CriteriaQuery/CriteriaBuilder 默认不支持,所以我使用 Interceptor 来修改原生查询。
问题是,SQL Server 不支持关键字 NULLS FIRST,所以我使用关键字:

case when column_name is null then 0 else 1 end, column_name

如果我想将数据库从 SQL Server 迁移到 Oracle(例如),那么我需要将 if-else 放入我的 Interceptor 中,选择我使用的方言,对吗?

我是这样说明它们的:

String dialect = ..............
if (dialect.equals("org.hibernate.dialect.SQLServerDialect")) { // get SQL Server dialect
     // put keyword "case when column_name is null then 0 else 1 end, column_name"
} else {
     // put keyword "NULLS FIRST/LAST"
}

如何在运行时获取方言配置(在 persistence.xml 中)?

【问题讨论】:

标签: java hibernate persistence.xml dialect


【解决方案1】:

以下内容非常适合我在 WildFly 14 中运行的 Java EE 应用程序中访问方言:

import org.hibernate.Session;
import org.hibernate.dialect.Dialect;
import org.hibernate.internal.SessionFactoryImpl;

...

@PersistenceContext
private EntityManager entityManager;

...

final Session session = (Session) entityManager.getDelegate();
final SessionFactoryImpl sessionFactory = (SessionFactoryImpl) session.getSessionFactory();
final Dialect dialect = sessionFactory.getJdbcServices().getDialect();
logger.info("Dialect: {}", dialect);

您需要将具有 provided 范围的 hibernate-core 依赖项添加到 pom.xml

【讨论】:

    【解决方案2】:

    如果你使用Spring+hibernate,试试这个

    @Autowired@Qualifier("sessionFactory") org.springframework.orm.hibernate3.LocalSessionFactoryBean sessionFactory; //Suppose using hibernate 3
    

    在你的方法中:

    sessionFactory.getHibernateProperties().get("hibernate.dialect")
    

    【讨论】:

      【解决方案3】:

      我从这篇文章中找到了答案:Resolve SQL dialect using hibernate

      感谢@Dewfy,

      解决办法如下:

      //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().equals("org.hibernate.dialect.SQLServerDialect")) {
      
      } else {
      
      }
      

      【讨论】:

      • 这样会更快,更不痛苦:String dialect = entityManager.getEntityManagerFactory().getProperties().getOrDefault("hibernate.dialect", "").toString();
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-04
      • 2013-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      相关资源
      最近更新 更多