Java Interview questions on Hibernate
Categories: EDUCATION
It's now time to review some questions derived from Hibernate, a well-known Java framework:
Q.1. When is it better to use plain SQL instead of ORM?
Ans. It's better to use plain SQL when:
(i) Complex queries need to be optimized for performance.
(ii) The database schema or query requirements are not well-supported by the ORM framework.
(iii) Direct control over SQL statements, database connections, or transactions is required.
Q.2. Difference between sorted and ordered collection?
Ans. In Java, a sorted collection maintains elements in a specific order defined by a comparator or by the natural ordering of elements, while an ordered collection maintains elements in the order they were inserted.
Q.3. How does second level cache work?
Ans. Second level cache in Hibernate stores objects in a shared cache region, typically across multiple sessions. When an entity is queried for the first time, it is fetched from the database and stored in the second level cache. Subsequent queries for the same entity can then be satisfied from the cache instead of hitting the database, improving performance.
Q.4. What is the difference between save() and persist() in Hibernate?
Ans. Both save() and persist() methods in Hibernate are used to save an entity to the database. However, save() returns the generated identifier immediately, while persist() doesn't guarantee immediate execution of the SQL INSERT statement; it may be executed later during flush time. Additionally, persist() is part of the JPA specification, while save() is specific to Hibernate.
Q.5. What is the difference between Hibernate and MyBatis?
Ans. (i) Hibernate is a full-fledged ORM framework that maps Java objects to database tables, manages database connections, and provides various querying mechanisms. MyBatis, on the other hand, is a lightweight persistence framework that uses SQL mapping files to map Java objects to SQL queries.
(ii) Hibernate is typically used for domain-driven development, where object-oriented modeling is prominent, while MyBatis is often preferred for projects where direct control over SQL queries is required, such as legacy database systems or complex SQL scenarios.
(iii) Hibernate provides caching mechanisms, automatic dirty checking, and transaction management, while MyBatis offers more control over SQL queries and mappings, allowing developers to write SQL queries directly.