package com.springboot.mvc; import java.util.Properties; import com.springboot.mvc.models.Customer; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; public class HibernateUtil { private static SessionFactory sessionFactory; public static SessionFactory getSessionFactory() { if (sessionFactory == null) { try { Configuration configuration = new Configuration(); // Hibernate settings equivalent to hibernate.cfg.xml's properties Properties settings = new Properties(); settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver"); settings.put(Environment.URL, "jdbc:mysql://192.168.99.100:3306/JDBC_spring_mvc_tutorial?useSSL=false&serverTimezone=UTC"); settings.put(Environment.USER, "cclee"); settings.put(Environment.PASS, "ccleedb12345"); settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL55Dialect"); settings.put(Environment.SHOW_SQL, "true"); settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); settings.put(Environment.HBM2DDL_AUTO, "create-drop"); configuration.setProperties(settings); configuration.addAnnotatedClass(Customer.class); // we add more and more classes here. ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { e.printStackTrace(); } } // Then: // Session session = sessionFactory.openSession(); // Transaction transaction = session.beginTransaction(); return sessionFactory; } }
Sunday, August 2, 2020
Hilbernate Database Configuration without XML
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment