import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.io.InputStream;
import java.util.Properties;
public class HibernateUtil {
private static final SessionFactory sessionFactory
= buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Load properties from YAML file
Properties properties = new Properties();
InputStream inputStream = HibernateUtil.class.getClassLoader().getResourceAsStream("hibernate.properties");
properties.load(inputStream);
// Build the Hibernate configuration
Configuration configuration = new Configuration();
configuration.setProperties(properties);
configuration.addAnnotatedClass(YourEntity.class); // Add
your entity class
// Build the SessionFactory with L2 cache
return configuration.buildSessionFactory();
} catch (Exception ex) {
System.err.println("SessionFactory creation failed: " + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
sessionFactory.close();
}
}
hibernate:
dialect: org.hibernate.dialect.MySQLDialect
connection.driver_class: com.mysql.cj.jdbc.Driver
connection.url: jdbc:mysql://localhost:3306/your_database
connection.username: your_username
connection.password: your_password
hibernate.hbm2ddl.auto: update
hibernate.show_sql: true
hibernate.format_sql: true
hibernate.cache.use_second_level_cache: true
hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory