You are here: Home / Topics / Hibernate Configuration using Java Singleton Class

Hibernate Configuration using Java Singleton Class

Filed under: Java on 2024-03-11 21:24:26

package com.mysite.firstJavaDbApp.config;

import java.util.Properties;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import com.mysite.firstJavaDbApp.beans.Employee;
import com.mysite.firstJavaDbApp.beans.Student;

public class HibernateDbConfig {
private SessionFactory sessionFactory;
private static HibernateDbConfig hibernateDbConfig;

private HibernateDbConfig() {
 Properties properties = new Properties();
 properties.put("hibernate.connection.username", "shyam");
 properties.put("hibernate.connection.password", "Pass@123");
 properties.put("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
 properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/javaee");
 properties.put("hibernate.connection.hbm2ddl.auto", "update");
 properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
 properties.put("hibernate.connection.show_sql", "true");

 Configuration configuration = new Configuration();
 configuration.setProperties(properties);
 configuration.addAnnotatedClass(Employee.class)
   .addAnnotatedClass(Student.class);
 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
   .applySettings(configuration.getProperties()).build();

 sessionFactory = configuration.buildSessionFactory();
}

public static HibernateDbConfig getInstance() {
 hibernateDbConfig = (hibernateDbConfig == null) ? new HibernateDbConfig() : hibernateDbConfig;
 return hibernateDbConfig;
}

public SessionFactory getSessionFactory() {
 return sessionFactory;
}

}
 

About Author:
J
Java Developer     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.