如何在运行时获取Hibernate方言

dan*_*pr4 9 java hibernate persistence.xml dialect


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

<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect">
Run Code Online (Sandbox Code Playgroud)

在我的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
Run Code Online (Sandbox Code Playgroud)

如果我想将数据库从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"
}
Run Code Online (Sandbox Code Playgroud)

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

mrt*_*rts 6

以下内容非常适合我访问在 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);
Run Code Online (Sandbox Code Playgroud)

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


小智 3

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

@Autowired@Qualifier("sessionFactory") org.springframework.orm.hibernate3.LocalSessionFactoryBean sessionFactory; //Suppose using hibernate 3
Run Code Online (Sandbox Code Playgroud)

并在你的方法中:

sessionFactory.getHibernateProperties().get("hibernate.dialect")
Run Code Online (Sandbox Code Playgroud)