Junior — Middle
Can you explain what SessionFactory is in the context of working with ORM in Java?
sobes.tech AI
Answer from AI
SessionFactory is a key interface in ORM frameworks for Java, such as Hibernate. It is responsible for creating and managing Session objects.
Session is a session for working with the database, through which CRUD operations (create, read, update, delete) are performed.
SessionFactory is usually created once at the start of the application and is thread-safe. It contains the database connection configuration, entity metadata, and first-level cache.
Example of using Hibernate:
// Creating SessionFactory (usually once)
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
// Obtaining a session for database operations
Session session = sessionFactory.openSession();
session.beginTransaction();
// operations with entities
session.save(entity);
session.getTransaction().commit();
session.close();
Thus, SessionFactory is a session factory that provides configuration and manages database connections in ORM.