12


在我的应用程序中,我使用 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 放在我的拦截器中,选择我使用的方言,对吗?

这就是我说明它们的方式:

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 中)?

4

3 回答 3

4

以下内容非常适合我在 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);

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

于 2019-07-30T14:15:04.223 回答
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 {

}
于 2014-11-28T07:26:36.277 回答
3

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

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

并在您的方法中:

sessionFactory.getHibernateProperties().get("hibernate.dialect")
于 2014-11-28T06:41:32.970 回答