11

I am using Hibernate latest version 4.3.5.Final.

My hibernate.cfg.xml file content:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost/Test</property>
    <property name="hibernate.connection.username">pankaj</property>
    <property name="hibernate.connection.password">xxxx</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

    <mapping resource="employee.hbm.xml"/>
</session-factory>

</hibernate-configuration>

Utility class to create SessionFactory:

package com.example;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

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

        SessionFactory sessionFactory = configuration.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() {
    return sessionFactory;
}
}

When I use it in my main() method, I get the following exception:

May 04, 2014 11:55:56 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Hibernate Configuration loaded
May 04, 2014 11:55:57 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.ExceptionInInitializerError
    at com.example.HibernateUtil.buildSessionFactory(HibernateUtil.java:25)
    at com.example.HibernateUtil.<clinit>(HibernateUtil.java:9)
    at com.example.HibernateMain.main(HibernateMain.java:26)
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)
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:209)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
    at com.example.HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
    ... 2 more

I have tried so many options and looked for online resources, hibernate docs but couldn't find what is missing here. Any help is appreciated.

12 Answers 12

37

Finally able to fix the issue, the issue is with the way SessionFactory is getting created.

For a starter, official document is the first place to go and I must say that Hibernate official documentation seems to be not update with latest version changes.

Fix is to apply the configuration settings to StandardServiceRegistryBuilder instance.

// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
        .applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration
        .buildSessionFactory(serviceRegistry);

Please refer my blog post here for more details.

Sign up to request clarification or add additional context in comments.

4 Comments

Where is StandardServiceRegistryBuilder located? in which package?
@M.S. if you can't find StandardServiceRegistryBuilder probably you're using Hibernate prior to version 4.3.
I am using the JBoss Tool Filal to integrate the Hibernate in JSF. So after doing the connfiguration from the Hibernate perspective and trying to run the new colsole configuration to export the Domain code, Hibernate xML Mapping, and DAO code I am getting the error. I think with my solution the SessionFactory is being gernarated too and I can not access it by the code.
17

I once faced the exact same problem, and it turned out that the issue was that I had not started the database service locally (which I see you are also using a local database). That simple!!!

1 Comment

My database is running fine, so that can't be an issue. I rechecked it with command line as well as Sequel Pro IDE (Mac).
1

Remove both lines of setting the dialect, Hibernate 4 does a fantastic job of determining which dialect to use based on the JDBC Driver you give it and the database that it connects too. You don't need to specify a dialect. If you force a dialect that is incorrect or doesn't quite match the driver (which can happen as dialects get updated more often than JDBC drivers do) Hibernate might not perform as expected.

Configuring Hibernate using a hibernate.cfg.xml is how things were done when using Hibernate 3. Hibernate 4 supports XML configuration within the Spring Application context. (I'm assuming that you are using Spring) It hooks in really smoothly. I suggest that you switch to using the new method of configuring Hibernate as your configuration doctype is set for Hibernate 3.

This is how you want to specify a dataSource for Hibernate 4 using the Spring application context.

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost/Test" />
    <property name="username" value="username" />
    <property name="password" value="password" />
</bean>

and then you wire it into your session factory like this:

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="package.where.your.annotated.objects.are" />
    <property name="hibernateProperties">
        <props>
            <!-- Uncomment this when testing -->
            <!--<prop key="hibernate.show_sql">true</prop>-->
            <prop key="hibernate.use_sql_comments">true</prop>
            <prop key="hibernate.hbm2ddl.auto">validate</prop>
        </props>
    </property>
</bean>
<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

7 Comments

Tried after removing both dialects, still got same exception. If I check exception class JdbcServicesImpl, it leads to MultiTenancyStrategy configurations but no help there.
Mixing old Hibernate config (Hibernate 3) with Hibernate 4 usually doesn't end well. See my update but I'd suggest you read how to configure Hibernate 4 within the Spring Application context. It also means you can get rid of that configuration class.
If you want to keep your mapping file (but IMHO using annotations on your objects is easier and more readable) you can specify your mapping file to the session factory rather than the packagesToScan property.
Thanks for the Spring integration, but I am new to Hibernate and using it in standalone application, so an example of "Hibernate only" would be helpful.
|
1

The same problem occurred to me with the mysql service running, correct credentials, but the database name was misspelled, so basically the database did not exist.

1 Comment

I'll add on to this that I had the user and password both spelled. Triple-check your settings in application.properties before running, everyone!
1

This will be OK

Configuration cfg = new Configuration().configure();

StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
        .applySettings(cfg.getProperties()).build();

SessionFactory sf = cfg.buildSessionFactory(serviceRegistry);

Session session = sf.openSession();

Comments

1

I encountered this issue when using the following:

  • Spring Framework / Data: 4.1.6;
  • Spring Boot: 1.2.3;
  • Hibernate provider for JPA: 4.3.8.

I had SSL enabled on the database side as part of the host-based authentication mechanism (using Postgres) and the issue was that I hadn't specified the SSL JVM properties related to the key store containing the certificate of the client app when starting the application:

-Djavax.net.ssl.keyStore=mykeystore.jks -Djavax.net.ssl.keyStorePassword=myPassword

Note: I understand the answer has already been answered, but I'm leaving this answer for future reference.

Comments

0

From the hibernate source code here, a StandardServiceRegistryBuilder instance is used to get different services from hibernate.cfg.xml, for example serviceRegistry.getService( JdbcServices.class ), serviceRegistry.getService( CacheImplementor.class ).

The old configuration.buildSessionFactory() method is as below now:

public SessionFactory buildSessionFactory() throws HibernateException {
    Environment.verifyProperties( properties );
    ConfigurationHelper.resolvePlaceHolders( properties );
    final ServiceRegistry serviceRegistry =  new StandardServiceRegistryBuilder()
            .applySettings( properties )
            .build();
    setSessionFactoryObserver(
            new SessionFactoryObserver() {
                @Override
                public void sessionFactoryCreated(SessionFactory factory) {
                }

                @Override
                public void sessionFactoryClosed(SessionFactory factory) {
                    ( (StandardServiceRegistryImpl) serviceRegistry ).destroy();
                }
            }
    );
    return buildSessionFactory( serviceRegistry );
}

Comments

0

You cal also fix the issue by creating the sesisonFactory this way.

SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory(
new StandardServiceRegistryBuilder().applySettings(new
Configuration().configure().getProperties()).build());

Comments

0

In my case I ran the configuration routine twice. I had automatic configuration (ie config from xml in resources) in one method, then I implemented a configuration by setting properties in another method but I forgot to bypass the former. As soon as I did, the error gone.

Comments

0

I had the exactly the same problem and the issue was, that my computer was not entered in the pg_hba.conf of the postgres database that allows which Clients(IP-Adresses) are allowed to speak with the database

Comments

0

It happened to me that I used the wrong username and password after I changed my connection string from remote address to localhost. Hope this will help.

Comments

0
// Create Configuration File and configure it.
    Configuration configuration=new Configuration();
    configuration.configure("com/sathya/config/emp.cfg.xml"); 
    // Create Service Registry
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    // Create Session Object using SessionFactory Interface
    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    Session session=sessionFactory.openSession();
    // new StandardServiceRegistryBuilder().applySettings(new Configuration().getProperties());
    // Session session=new Configuration().buildSessionFactory(new StandardServiceRegistryBuilder().build()).openSession();

1 Comment

Don,t Use comment Part as It throws Error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.