I was following Hibernate Official Documentation to create a basic hibernate application with version 4.3.5.Final. When I executed the application, I got hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
even though all the configuration seemed fine to me.
It took me long time to solve the problem and it turned out to be with the way SessionFactory
instance was getting created. My utility class to create SessionFactory instance was like below.
package com.journaldev.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class SessionFactoryUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory(new StandardServiceRegistryBuilder().build());
return sessionFactory;
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
}
And I was getting following stack trace:
May 07, 2014 7:11:59 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
May 07, 2014 7:12:00 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: employee.hbm.xml
May 07, 2014 7:12:00 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
May 07, 2014 7:12:00 PM org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator initiateService
WARN: HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections
Initial SessionFactory creation failed.org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
Exception in thread "main" java.lang.NullPointerException
at com.journaldev.hibernate.main.HibernateMain.main(HibernateMain.java:38)
From the logs it’s clear that Configuration class was able to find the hibernate configuration file and it has hibernate.dialect
defined, so the exception was not making any sense.
After some research and debugging, I was able to fix it. The part that is missing in the official documentation is that we need to apply the configuration properties to StandardServiceRegistryBuilder
. When I changed the utility class to below, everything worked like a charm.
package com.journaldev.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class SessionFactoryUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
System.out.println("Hibernate Configuration loaded");
//apply configuration property settings to StandardServiceRegistryBuilder
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate serviceRegistry created");
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
}
Notice the StandardServiceRegistryBuilder().applySettings
call where configuration properties are passed. Hibernate is still evolving and every version comes with a lot of changes and I feel that documentation part is lagging. I hope this will help someone fixing the issue rather than wasting a lot of time debugging.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
I have implemented in the same way but still getting the same error WARN : org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator - HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections Initial SessionFactory creation failed.org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when ‘hibernate.dialect’ not set Exception in thread “main” java.lang.ExceptionInInitializerError at harvard.dvs.videostats.util.DataSourse.buildSessionFactory(DataSourse.java:55) at harvard.dvs.videostats.util.DataSourse.getSessionFactory(DataSourse.java:61) at harvard.dvs.videostats.dao.impl.CourseLVPTDaoImpl.getVideoTopics(CourseLVPTDaoImpl.java:25) at harvard.dvs.videostats.action.bean.MainTest.testCall(MainTest.java:56) at harvard.dvs.videostats.action.bean.MainTest.main(MainTest.java:27) Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when ‘hibernate.dialect’ not set at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104) private static SessionFactory sessionFactory; private static SessionFactory buildSessionFactory() { try { Configuration configuration=new Configuration().configure(“hibernate.cfg.xml”); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); return configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { } } public static SessionFactory getSessionFactory() { if(sessionFactory == null) sessionFactory = buildSessionFactory(); return sessionFactory; }
- jose
Use debugger to pinpoint where is the error, it could be that hibernate.cfg.xml is not in classpath. Also check the hibernate version you are using, I am working on Hibernate 4.
- Pankaj
Hi Pankaj, Thank you very much for your help running this, I am new to hibernate and just like you was trying to build a sample program using their ref documentation. When I encountered this error , after much search I gave up and used sessionFactory = new Configuration().configure(“main/resources/hibernate.cfg.xml”).buildSessionFactory() which is deprecated, I then came across your post on stackoverflow, and followed the link here and this worked. Thanks once again.
- Bruce
I had the same situation :) Thank you Kumar!
- IvanDurov
THANK YOU VERY MUCH for this precise explanation. It just solved my problem!
- tab
Thanks – this worked!
- Mike
Usually we think that the best reference about a project is its official documentation. But I am surprised of the many mistakes in Hibernate Official Site. Thanks a lot for the help!
- Gleiton
thank you very much, i waste long time on this .
- hlx
Thanks. Helped me solve te problem
- Arun Menon
Hi Pankaj, thanks very much. This saved me a lot of time. Should we contact Hibernate team to let them do something about this?
- Evan
Thank you so much for this solution!! It was just perfect, saved me a looong time!
- Erizo
Good day I get this kind of Error what causes it:org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘userController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ngm.service.UserService com.ngm.controller.UserController.userService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘userService’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ngm.dao.UserDao com.ngm.service.UserServiceImpl.userDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘userDaoImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.ngm.dao.UserDaoImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/sdnext-servlet.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when ‘hibernate.dialect’ not set org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:602) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:521) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:462) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:158) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655) org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523) java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Unknown Source)
- Mohau
Thanks for your post! It’s helped me a lot.
- Jonathan Campos
many thx mate your post just made my day! it’s weird that their developer didnt update their getting start example related to the evolving…
- djpath
Thank you very much sir. You made my day
- Soujanya
Thank you.
- raiym
I also wanted to express my thanks. I also found the hibernate documentation kind of weird… Amazingly one runs into this very problem, when you try to follow the “first app” section at the start of the documentation of version 4.3.11.FINAL. It surprises me, that this doesn’t get more attention. Also the documentation to version 5 is very incomplete… without any clear notice of that, or at least not clear enough for me to notice, until I compared the documentation with previous ones.
- Marc
Thank you all, You really saved my night!!! It works
- mha
Thanks! It did help me, I was getting the same error. I didn’t understand the part that Hibernate is able to find configuration file, since it says “hibernate.dialect”, which implies opposite!
- Ravi Arora
thanks… it worked like a charm. U saved my night. :)
- Shashank
Hi Pankaj , I’m creating using below config but still getting same issue. Can you please help. import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.util.Properties; @Configuration @EnableTransactionManagement @PropertySource({“classpath:pgsql.properties”}) @ComponentScan({“path”}) public class PersistenceConfig { @Autowired private Environment env; public PersistenceConfig() { super(); } @Bean public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(getDataSource()); sessionFactory.setPackagesToScan(new String[]{“path”}); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Bean HikariDataSource getDataSource() { Properties props = new Properties(); props.setProperty(“dataSourceClassName”, “value”); props.setProperty(“dataSource.user”, “value”); props.setProperty(“dataSource.password”, “value”); props.setProperty(“dataSource.databaseName”, “value”); props.setProperty(“dataSource.serverName”, “value”); props.setProperty(“dataSource.portNumber”, “value”); //props.put(“dataSource.logWriter”, new PrintWriter(System.out)); HikariConfig config = new HikariConfig(props); return new HikariDataSource(config); } @Bean public PlatformTransactionManager hibernateTransactionManager() { final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactory().getObject()); return transactionManager; } private final Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty(“hibernate.hbm2ddl.auto”, “create-drop”); hibernateProperties.setProperty(“hibernate.dialect”, “org.hibernate.dialect.PostgreSQLDialect”); hibernateProperties.setProperty(“hibernate.show_sql”, “true”); // hibernateProperties.setProperty(“hibernate.format_sql”, “true”); // hibernateProperties.setProperty(“hibernate.globally_quoted_identifiers”, “true”); // Envers properties // hibernateProperties.setProperty(“org.hibernate.envers.audit_table_suffix”, env.getProperty(“envers.audit_table_suffix”)); return hibernateProperties; } }
- Mike
Very useful article. Finally got my app working. Thank you.
- David Gesrib