Hibernate / Hibernate 7 Basics Interview Questions
What is the Hibernate SessionFactory and how do you create one?
The SessionFactory is the central, thread-safe, immutable configuration object. It is expensive to create and should be instantiated once per application lifecycle.
Configuration config = new Configuration(); config.setProperty("hibernate.connection.url", "jdbc:postgresql://localhost:5432/mydb"); config.setProperty("hibernate.connection.username", "user"); config.setProperty("hibernate.connection.password", "secret"); config.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect"); config.setProperty("hibernate.hbm2ddl.auto", "validate"); config.setProperty("hibernate.show_sql", "true"); config.addAnnotatedClass(Product.class); config.addAnnotatedClass(Order.class); // Build once, reuse everywhere: SessionFactory sf = config.buildSessionFactory(); // Usage: try (Session session = sf.openSession()) { session.beginTransaction(); // operations session.getTransaction().commit(); }
More Related questions...