I have created a separate utility class for SessionFactory and below is my code:
package com.Hibernate.Util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
System.out.println("Hibernate configuration loading......");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
System.out.println("Hibernate serviceRegistry created.....");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
System.out.println("SessionFactory creation failure.....");
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory1() {
if (sessionFactory == null)
sessionFactory = buildSessionFactory();
return sessionFactory;
}
}
Hibernate configuration file hibernate.cfg.xml file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.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.username">root</property>
<property name="hibernate.connection.password">root.123</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/Hibernate</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>
<mapping class="com.Hibernate.Model.Employee"></mapping>
<mapping class="com.Hibernate.Model.Address"></mapping>
</session-factory>
</hibernate-configuration>
Below class calls the SessionFactory method buildSessionFactory HQLExample.java:
package com.Hibernate.Main;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.Hibernate.Model.Employee;
import com.Hibernate.Util.HibernateUtil;
public class HQLExample {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory1();
System.out.println(sessionFactory);
Session session = sessionFactory.getCurrentSession();
}
}
The code is executing but the tables are being not created. Can someone please tell me what would be the issue with the code???