How to Configure Hibernate without using hibernate.cfg.xml File

Configure Hibernate without using hibernate.cfg.xml File

In this tutorial, I am attaching simple program about, How to Configure Hibernate without using hibernate.cfg.xml File.

The SessionProvider class is responsible to provide the session for the Database Transaction. The org.hibernate.Session Object is retrieved from org.hibernate.SessionFactory. Which is build based on the Configuration details that we provided for specific database in org.hibernate.cfg.Configuration Object. In this tutorial, I have provided configuration details for MySQL database such as.

  • hibernate.dialect
  • hibernate.connection.driver_class
  • hibernate.connection.url
  • hibernate.connection.username
  • hibernate.connection.password
package com.dineshkrish.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

 * @author Dinesh Krishnan

public class SessionProvider {

	private static Session session;
	private static Configuration configuration;
	private SessionProvider() { }
	static {
		configuration = new Configuration()
		.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
	    .setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
	    .setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/employee")
	    .setProperty("hibernate.connection.username", "root")
	    .setProperty("hibernate.connection.password", "")
	    .setProperty("hibernate.show_sql", "true")
	    .setProperty("", "update")
	    // Your Mapping Class
	public static Session getSession() {
		SessionFactory factory = configuration.buildSessionFactory();
		session = factory.openSession();
		return session;

package com.dineshkrish.hibernate;

import org.hibernate.Session;

public class Application {

	public static void main(String[] args) {
		// Getting the Session Object 
		Session session = SessionProvider.getSession();
		// You can do transaction here...


2. Hibernate API Documentation