How to get hibernate dialogs at runtime


In my application, I use Hibernate with a SQL Server database, so I installed

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

in my persistence.xml.

In some cases, I want to sort records with NULL enabled, I use the NULLS FIRST keyword.
Since it is not supported by default CriteriaQuery / CriteriaBuilder in Hibernate, I use Interceptor to modify my own query.
The problem is that the NULLS FIRST keyword is not supported in SQL Server, so I use the keyword:

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

If I want to transfer the database from SQL Server to Oracle (for example), then I need to put if-else in my Interceptor, choosing the dialect that I use, right?

Here is how I illustrate them:

 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" } 

How can I get the dialect configuration (in persistence.xml) at runtime?

+9
source share
3 answers

If you are using Spring + hibernate try

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

and in your method:

 sessionFactory.getHibernateProperties().get("hibernate.dialect") 
+4
source

I found the answer from this post: Allow SQL dialect using sleep mode

Thanks for @Dewfy,

here is the solution:

 //take from current EntityManager current DB Session Session session = (Session) em.getDelegate(); //Hibernate 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 { } 
+1
source

The following is good for accessing a dialect in a Java EE application running in WildFly 14:

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

You need to add the hibernate-core dependency with the provided scope in pom.xml .

0
source

Source: https://habr.com/ru/post/1207858/


All Articles