Connection cannot be null hibernate exception

Siva Subramaniam picture Siva Subramaniam · May 22, 2012 · Viewed 13.5k times · Source

I'm a newbie to hibernate . I get this exception "Connection cannot be null when hibernate.dialect is not set" when i try to run it. I've set the dialect properly.

This is the hibernate.cfg.xml file

<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysql</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">create</property>

<mapping class="org.siva.model.UserDetails"/>
</session-factory>
</hibernate-configuration>

The model class.

@Entity
public class UserDetails {
  @Id
  private int userID;
  private String userName;

  public int getUserID() {
    return userID;
  }
  public void setUserID(int userID) {
    this.userID = userID;
  }
  public String getUserName() {
    return userName;
  }
  public void setUserName(String userName) {
    this.userName = userName;
  }
}

The main class

public class HibernateTest {

public static void main(String[] args) {
   UserDetails user=new UserDetails();
   user.setUserID(1);
   user.setUserName("firstUser");
   Configuration configuration=new Configuration();
   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();        
   SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
   Session session=sessionFactory.openSession();
   session.beginTransaction();
   session.save(user);
   session.getTransaction().commit();

}

}

Answer

Johanna picture Johanna · May 22, 2012

You forgot to configure your configuration. Use for example this call

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