Excellent — here’s a clear, interview-level answer:
✅ What is a Session in Hibernate?
Answer:
A Session in Hibernate is the primary interface between your Java application and the database. It represents a single unit of work (a conversation with the database) and provides methods for:
- CRUD operations: Saving, updating, deleting, and retrieving entities.
- Transaction management: Starting, committing, or rolling back transactions.
- Query execution: Creating and executing HQL, Criteria, or native SQL queries.
Excellent — here’s a clear, interview-level answer:
✅ What is a Session in Hibernate?
Answer:
A Session in Hibernate is the primary interface between your Java application and the database. It represents a single unit of work (a conversation with the database) and provides methods for:
- CRUD operations: Saving, updating, deleting, and retrieving entities.
- Transaction management: Starting, committing, or rolling back transactions.
- Query execution: Creating and executing HQL, Criteria, or native SQL queries.
- Connection management: Abstracting and managing database connections via the configured connection pool.
- Caching: Acting as a first-level (mandatory) cache, storing entities you’ve loaded or saved within the same session.
🔹 Key characteristics:
✅ Not thread-safe: a Session
instance should be used by only one thread at a time.
✅ Short-lived: typically created per request, per transaction, or per service call.
✅ Lightweight: opening and closing sessions is inexpensive when connection pooling is used.
✅ First-level cache: objects loaded in a session are cached, avoiding redundant database queries.
🔹 Typical usage example:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = new User();
user.setUsername("john_doe");
session.save(user);
tx.commit();
session.close();
🔹 1) Executing an HQL Query
HQL is Hibernate’s object-oriented query language that lets you query entities using their class and field names, not table/column names.
For example, retrieving a User
by username:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hql = "FROM User WHERE username = :username";
User user = session.createQuery(hql, User.class)
.setParameter("username", "john_doe")
.uniqueResult();
System.out.println("Found user: " + user.getEmail());
tx.commit();
session.close();
✅ What’s happening:
FROM User
tells HQL to query theUser
entity (not the table directly).:username
is a named parameter.- Hibernate automatically translates this into the appropriate SQL for your database.
🔹 2) Executing a Native SQL Query
Sometimes you need raw SQL, e.g., for complex queries or database-specific features. Hibernate supports native queries for these cases.
For example:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String sql = "SELECT * FROM users WHERE username = :username";
Object[] result = (Object[]) session.createNativeQuery(sql)
.setParameter("username", "john_doe")
.getSingleResult();
System.out.println("Found user ID: " + result[0] + ", username: " + result[1]);
tx.commit();
session.close();
✅ What’s happening:
createNativeQuery(sql)
allows raw SQL.- The result comes back as an
Object[]
orList<Object[]>
because Hibernate doesn’t know your entity mapping automatically with native queries (unless you explicitly map the result).
🔹 Bonus: Mapping native query results directly to entities
If you want native SQL and automatic mapping to your entity:
String sql = "SELECT * FROM users WHERE username = :username";
User user = session.createNativeQuery(sql, User.class)
.setParameter("username", "john_doe")
.uniqueResult();
✅ This way, Hibernate maps the native SQL result to your User
entity fields.
🔹 Key takeaway:
- Use HQL for most queries — it’s portable and uses entities.
- Use native SQL only when needed, e.g., for vendor-specific features or very complex queries.