Junior — Middle
What are the main components and mechanisms implemented in Hibernate for working with a database?
sobes.tech AI
Answer from AI
Hibernate is an ORM framework for Java that simplifies working with databases by hiding SQL and JDBC details. The main components and mechanisms of Hibernate include:
- SessionFactory — a factory for creating sessions (Session), usually created once per application.
- Session — the primary API for interacting with the database, through which CRUD operations are performed.
- Transaction — manages transactions to ensure atomicity of operations.
- Query — a mechanism for executing database queries, supporting HQL (Hibernate Query Language) and Criteria API.
- Entity — classes mapped to database tables via annotations or XML mapping.
- Cache — a two-level caching system (first-level cache at the session level and second-level cache at the SessionFactory level) to optimize data access.
Example of using a Session to save an object:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = new User();
user.setName("Ivan");
session.save(user);
tx.commit();
session.close();
Thus, Hibernate manages the lifecycle of objects, transactions, and data transformation between Java objects and database tables.