Top 60+ Hibernate interview questions and answers for freshers

Are are you preparing for Hibernate interview. To help you get ready, we’ve compiled 60+ most essential and commonly asked Hibernate interview questions and answers for freshers. This comprehensive guide covers fundamental concepts, core features, and best practices in Hibernate, ensuring you have a solid foundation to crack Hibernate interview.

Hibernate interview questions and answers for freshers
Hibernate interview questions and answers for freshers

Hibernate interview questions and answers for freshers

1. What is Hibernate?
2. Explain ORM and its advantages.
3. What are the key features of Hibernate?
4. What are the core interfaces of Hibernate?
5. What is the difference between Session and SessionFactory?
6. What is HQL?
7. What is a persistent class in Hibernate?
8. Explain the Hibernate architecture.
9. How does Hibernate manage transactions?
10. What is the difference between get() and load()?
11. What is lazy loading?
12. What is eager loading?
13. Explain caching in Hibernate.
14. What are the different types of Hibernate caching?
15. Explain the Hibernate configuration file.
16. What is the role of the hibernate.cfg.xml file?
17. What is a Hibernate dialect?
18. What is the criteria API in Hibernate?
19. What are the states of an object in Hibernate?
20. Explain transient, persistent, and detached states.
21. What are Hibernate Annotations?
22. What is the use of @Entity annotation?
23. What is the @Id annotation used for?.
24. Explain @Table annotation in Hibernate.
25. What is the difference between merge() and update() in Hibernate?
26. What is a proxy in Hibernate?
27. What is the Session.close() method?
28. What are named queries in Hibernate?
29. What is @GeneratedValue in Hibernate?
30. What is the purpose of @OneToOne, @OneToMany, and @ManyToOne annotations?
31. What is the Hibernate Session.persist() method?
32. What is Hibernate Query Language (HQL) and how is it different from SQL?
33. How does Hibernate handle JDBC connections?
34. What are the advantages of using Hibernate over JDBC?
35. Explain the difference between save() and persist() methods.
36. What is the purpose of the @MappedSuperclass annotation?
37. Can you use SQL queries in Hibernate?
38. What is the Interceptor in Hibernate?
39. How can we use multiple databases in Hibernate?
40. What is the difference between clear() and evict() methods in Hibernate?
41. What is batch processing in Hibernate?
42. Explain the @Inheritance strategy in Hibernate.
43. What is the purpose of the @Embeddable annotation?
44. How does Hibernate handle primary key generation?
45. What is optimistic locking in Hibernate?
46. How does Hibernate support pagination?
47. Explain how to handle composite keys in Hibernate.
48. What is the role of @Temporal annotation?
49. What are natural IDs in Hibernate?
50. What is @Cacheable annotation?
51. How do you perform a join in HQL?
52. What is the @SecondaryTable annotation used for?
53. How does Hibernate handle cascading in relationships?
54. What are @Formula and computed properties in Hibernate?
55. How does @ManyToMany mapping work in Hibernate?
56. What is FlushMode in Hibernate?
57. How do you handle concurrency in Hibernate?
58. Explain the purpose of Session.refresh() method.
59. What is JPA in the context of Hibernate?
60. What is the use of the @OrderBy annotation?
61. What are collection mappings in Hibernate?
62. What is EntityManager in JPA and how does it relate to Hibernate?

1. What is Hibernate?

Answer:

Hibernate is an open-source ORM (Object-Relational Mapping) framework for Java. It simplifies database interactions by mapping Java classes to database tables, allowing developers to work with Java objects rather than SQL queries.

2. Explain ORM and its advantages.

Answer:

ORM (Object-Relational Mapping) is a technique for converting data between incompatible systems (Java objects and relational databases). Advantages include improved productivity, reduced complexity in data handling, and simplified maintenance.

3. What are the key features of Hibernate?

Answer:

Some key features include ORM, HQL (Hibernate Query Language), caching, lazy loading, automatic table generation, and transaction management.

4. What are the core interfaces of Hibernate?

Answer:

Core interfaces in Hibernate include Session, SessionFactory, Transaction, Query, and Configuration.

5. What is the difference between Session and SessionFactory?

Answer:

SessionFactory is a factory for creating Session instances. It’s created once per application and is thread-safe. Session is a single-threaded object that performs CRUD operations on entities and is not thread-safe.

6. What is HQL?

Answer:

HQL (Hibernate Query Language) is an object-oriented query language similar to SQL but focused on querying Java objects, not tables.

7. What is a persistent class in Hibernate?

Answer:

A persistent class is a Java class mapped to a database table. It follows certain conventions like a default constructor, an identifier property, and proper access modifiers for attributes.

8. Explain the Hibernate architecture.

Answer:

Hibernate architecture consists of various layers like Configuration, SessionFactory, Session, Transaction, and Query. It handles the lifecycle of data, mapping, and query translation from Java objects to SQL.

9. How does Hibernate manage transactions?

Answer:

Hibernate manages transactions using the Transaction interface, which can be either programmatically controlled or declarative, leveraging Java’s transaction API or JTA for distributed transactions.

10. What is the difference between get() and load()?

Answer:

get() returns null if the object isn’t found, while load() throws an ObjectNotFoundException. load() returns a proxy, while get() directly hits the database.

11. What is lazy loading?

Answer:

Lazy loading delays the initialization of an object until it’s actually needed, which improves performance by avoiding unnecessary data loading.

12. What is eager loading?

Answer:

Eager loading loads all associated entities immediately with the main entity, which can sometimes reduce the number of database calls.

13. Explain caching in Hibernate.

Answer:

Hibernate has a two-level caching mechanism: first-level cache (associated with Session) and second-level cache (associated with SessionFactory). First-level caching is by default enabled to improve performance.

14. What are the different types of Hibernate caching?

Answer:

Hibernate supports first-level cache, second-level cache, and query cache. The second-level cache can be configured using caching providers like EHCache, OSCache, or Infinispan.

15. Explain the Hibernate configuration file.

Answer:

The Hibernate configuration file (usually hibernate.cfg.xml) is an XML file that configures Hibernate settings like database connection, mapping files, dialect, and caching settings.

16. What is the role of the hibernate.cfg.xml file?

Answer:

hibernate.cfg.xml provides configuration parameters for Hibernate, including connection URL, username, password, dialect, and mapping resources.

17. What is a Hibernate dialect?

Answer:

Dialect is a configuration that allows Hibernate to generate SQL optimized for the specific database being used (e.g., MySQLDialect, OracleDialect).

18. What is the criteria API in Hibernate?

Answer:

The Criteria API allows developers to build dynamic queries programmatically using Java objects instead of hardcoded SQL or HQL, enabling greater flexibility.

19. What are the states of an object in Hibernate?

Answer:

An object in Hibernate can be in one of three states: transient, persistent, or detached.

20. Explain transient, persistent, and detached states.

Answer:

  • Transient: The object is created but not associated with a Session.
  • Persistent: The object is associated with a Session and has a corresponding row in the database.
  • Detached: The object is previously persistent but is no longer associated with a Session.

21. What are Hibernate Annotations?

Answer:

Hibernate annotations allow developers to define mappings directly in the Java classes, making it easier to manage without XML configurations (e.g., @Entity, @Table, @Id).

22. What is the use of @Entity annotation?

Answer:

@Entity is used to declare a class as an entity, meaning it is mapped to a database table.

23. What is the @Id annotation used for?

Answer:

@Id is used to specify the primary key of an entity.

24. Explain @Table annotation in Hibernate.

Answer:

@Table is used to provide table details for an entity, such as its name, schema, and catalog.

25. What is the difference between merge() and update() in Hibernate?

Answer:

update() is used for attaching a detached entity to a session, while merge() creates a new copy of the detached entity and merges changes.

26. What is a proxy in Hibernate?

Answer:

A proxy is an object used for lazy loading. Hibernate creates a proxy that loads data only when the object is accessed.

27. What is the Session.close() method?

Answer:

Session.close() closes the session and releases resources. Once closed, the session cannot be reused.

28. What are named queries in Hibernate?

Answer:

Named queries are static queries defined in the mapping metadata using annotations or XML, improving readability and reusability.

29. What is @GeneratedValue in Hibernate?

Answer:

@GeneratedValue is used to specify the generation strategy for primary key values, such as AUTO, SEQUENCE, TABLE, or IDENTITY.

30. What is the purpose of @OneToOne, @OneToMany, and @ManyToOne annotations?

Answer:

These annotations are used to define relationships between entities in Hibernate, representing one-to-one, one-to-many, and many-to-one associations, respectively.

31. What is the Hibernate Session.persist() method?

Answer:

Session.persist() is used to save an entity but does not guarantee the generation of an identifier immediately.

32. What is Hibernate Query Language (HQL) and how is it different from SQL?

Answer:

HQL is a database-independent query language similar to SQL but operates on persistent objects rather than directly on database tables.

33. How does Hibernate handle JDBC connections?

Answer:

Hibernate abstracts the JDBC connection using configurations specified in hibernate.cfg.xml and establishes connections via the configured DataSource or DriverManager.

34. What are the advantages of using Hibernate over JDBC?

Answer:

Hibernate simplifies development, manages caching, provides automated transactions, and supports database independence and portability.

35. Explain the difference between save() and persist() methods.

Answer:

Both save() and persist() save entities to the database, but save() returns the generated ID, while persist() doesn’t. Additionally, persist() is part of the JPA standard.

36. What is the purpose of the @MappedSuperclass annotation?

Answer:

@MappedSuperclass is used to define a superclass whose properties are inherited by subclasses but does not create a table in the database.

37. Can you use SQL queries in Hibernate?

Answer:

Yes, SQL queries can be used in Hibernate by using the createSQLQuery() method in the Session interface.

38. What is the Interceptor in Hibernate?

Answer:

Interceptors are used to listen to events or to modify an object before or after a certain action is performed, such as insert or update.

39. How can we use multiple databases in Hibernate?

Answer:

Multiple databases can be configured by creating multiple SessionFactory instances, each configured for a different database.

40. What is the difference between clear() and evict() methods in Hibernate?

Answer:

clear() removes all objects from the session cache, while evict() removes a specific object.

41. What is batch processing in Hibernate?

Answer:

Batch processing allows bulk insertion, updating, or deletion to be done in groups, reducing the database round-trips.

42. Explain the @Inheritance strategy in Hibernate.

Answer:

Hibernate supports inheritance strategies like SINGLE_TABLE, TABLE_PER_CLASS, and JOINED to map inheritance hierarchies.

43. What is the purpose of the @Embeddable annotation?

Answer:

@Embeddable is used for value-type objects which can be embedded within other entities using the @Embedded annotation.

44. How does Hibernate handle primary key generation?

Answer:

Hibernate provides multiple strategies like AUTO, IDENTITY, SEQUENCE, and TABLE for primary key generation via the @GeneratedValue annotation.

45. What is optimistic locking in Hibernate?

Answer:

Optimistic locking prevents data loss due to concurrent updates by checking a version field before committing changes.

46. How does Hibernate support pagination?

Answer:

Hibernate provides methods like setFirstResult() and setMaxResults() in the Query interface to limit results and implement pagination.

47. Explain how to handle composite keys in Hibernate.

Answer:

Composite keys can be handled using the @Embeddable class with multiple fields or by using the @IdClass annotation.

48. What is the role of @Temporal annotation?

Answer:

@Temporal specifies the precision of the date or time value to be stored, such as DATE, TIME, or TIMESTAMP.

49. What are natural IDs in Hibernate?

Answer:

A natural ID is a unique business key identifier for an entity. Hibernate provides support for it via the @NaturalId annotation.

50. What is @Cacheable annotation?

Answer:

@Cacheable specifies that the entities or queries should be cached if the caching is enabled in the Hibernate configuration.

51. How do you perform a join in HQL?

Answer:

Joins can be performed in HQL using keywords like JOIN, LEFT JOIN, and FETCH JOIN to associate entities or select specific fields.

52. What is the @SecondaryTable annotation used for?

Answer:

@SecondaryTable allows mapping a single entity across multiple tables.

53. How does Hibernate handle cascading in relationships?

Answer:

Cascading, controlled by annotations like @Cascade, automates operations (save, delete, etc.) across entity relationships.

54. What are @Formula and computed properties in Hibernate?

Answer:

@Formula is used to map a property to a computed value from SQL expressions rather than a database column.

55. How does @ManyToMany mapping work in Hibernate?

Answer:

@ManyToMany maps a collection that is associated with another entity, creating a join table to represent the association.

56. What is FlushMode in Hibernate?

Answer:

FlushMode determines when session changes are synchronized with the database, with modes like AUTO, COMMIT, ALWAYS, and MANUAL.

57. How do you handle concurrency in Hibernate?

Answer:

Concurrency can be handled using versioning (optimistic locking) or by leveraging database locks (pessimistic locking).

58. Explain the purpose of Session.refresh() method.

Answer:

refresh() updates the entity’s state in the session with the latest data from the database.

59. What is JPA in the context of Hibernate?

Answer:

JPA (Java Persistence API) is a standard for ORM, while Hibernate is an implementation of JPA, offering additional features.

60. What is the use of the @OrderBy annotation?

Answer:

@OrderBy specifies the sorting of elements in a collection when retrieved from the database.

61. What are collection mappings in Hibernate?

Answer:

Collection mappings define how collections (like sets, lists, or maps) are represented and persisted in the database tables.

62. What is EntityManager in JPA and how does it relate to Hibernate?

Answer:

EntityManager is JPA’s API for managing entities. In Hibernate, it can be used as an alternative to the Session API when working in JPA mode.

Learn More: Carrer Guidance

Terraform interview questions and answers for all levels

Rest API interview questions and answers for all levels

Mysql interview questions and answers for experienced

Mysql interview questions and answers for freshers

Python interview questions and answers for data analyst experienced

Python interview questions and answers for data analyst freshers

Splunk interview questions and answers

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

    Comments