📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Let's begin with what is ORM?
1. What is ORM?
2. What is Hibernate Framework?
3. What is Java Persistence API (JPA)?
4. How does Hibernate relate to JDBC?
5. Explain Hibernate Architecture?
SessionFactory (org.hibernate.SessionFactory)
Session (org.hibernate.Session)
Transaction (org.hibernate.Transaction)
6. What are the important benefits of using Hibernate Framework?
- Hibernate is awesome as it eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
- Hibernate framework provides support for XML as well as JPA annotations, which makes our code implementation independent.
- Hibernate framework provides a powerful query language that is Hibernate Query Language(HQL) which is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism, and association, etc.
- Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating Hibernate with Spring applications.
- Hibernate supports lazy initialization using proxy objects and performs actual database queries only when it’s required.
- Hibernate framework provides a cache (first level and second level) that helps us in getting the better performance of the Java applications.
- Hibernate framework supports native SQL queries so Hibernate is suitable for a database vendor-specific feature.
- Overall Hibernate is the best choice in the current market for the ORM tool, it contains all the features that you will ever need in an ORM tool.
7. What are the advantages of Hibernate over JDBC?
- Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks cleaner and readable.
- Hibernate supports inheritance, associations, and collections. These features are not present with JDBC API.
- Hibernate implicitly provides transaction management, in fact, most of the queries can’t be executed outside a transaction. In JDBC API, we need to write code for transaction management using commit and rollback.
- JDBC API throws SQLException which is a checked exception, so we need to write a lot of try-catch block code. Most of the time it’s redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throws JDBCException or HibernateException un-checked exception, so we don’t need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.
- Hibernate Query Language (HQL) is more object-oriented and close to a Java programming language. For JDBC, we need to write native SQL queries.
- Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
- Hibernate provides an option through which we can create database tables too, for JDBC tables must exist in the database.
- Hibernate configuration helps us in using JDBC-like connection as well as JNDI DataSource for a connection pool. This is a very important feature in enterprise applications and completely missing in JDBC API.
- Hibernate supports JPA annotations, so the code is independent of the implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.
8. What is Hibernate Configuration File?
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate_db?useSSL=false</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create-drop</property>
<!-- dbcp connection pool configuration -->
<property name="hibernate.dbcp.initialSize">5</property>
<property name="hibernate.dbcp.maxTotal">20</property>
<property name="hibernate.dbcp.maxIdle">10</property>
<property name="hibernate.dbcp.minIdle">5</property>
<property name="hibernate.dbcp.maxWaitMillis">-1</property>
<mapping class="net.javaguides.hibernate.entity.Student" />
</session-factory>
</hibernate-configuration>
9. What are possible ways to configure object-table mapping?
- Using XML based hibernate mapping
- Annotation-based hibernate mapping
10. What is Hibernate SessionFactory and How to Configure it?
11. Hibernate SessionFactory is a Thread-Safe?
12. What is Hibernate Session and How to Get it?
13. Hibernate Session is a Thread-Safe?
14. What is the difference Between openSession and getCurrentSession?
<property name="hibernate.current_session_context_class">thread</property>
15. Explain Hibernate Transaction Interface
A transaction is associated with a Session and instantiated by calling session.beginTransaction().
The methods of Transaction interface are as follows:
- void begin() - starts a new transaction.
- void commit() - ends the unit of work unless we are in FlushMode.NEVER.
- void rollback() - forces this transaction to rollback.
- void setTimeout(int seconds) - it sets a transaction timeout for any transaction started by a subsequent call to begin on this instance.
- boolean isAlive() - checks if the transaction is still alive.
- void registerSynchronization(Synchronization s) - registers a user synchronization callback for this transaction.
- boolean wasCommited() - checks if the transaction is committed successfully.
- boolean wasRolledBack() - checks if the transaction is rolled back successfully.
16. What is the Requirement for a Java Object to Become a Hibernate Entity Object?
- The class must be annotated with the javax.persistence.Entity annotation.
- The class must have a public or protected, no-argument constructor. The class may have other constructors.
- The class must not be declared final. No methods or persistent instance variables must be declared final.
- If an entity instance is passed by value as a detached object, such as through a session bean's remote business interface, the class must implement the Serializable interface.
- Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes.
- Persistent instance variables must be declared private, protected, or package-private and can be accessed directly only by the entity class's methods. Clients must access the entity's state through accessor or business methods.
17. What is the Difference Between Hibernate Session get() and load() method?
- The key difference between the get() method and load() method is that load() method will throw an exception if an object with id passed to them is not found, but get() method will return null.
- The second important difference is that load() method can return proxy without hitting the database unless required (when you access any attribute other than id) but the get() method always go to the database, so sometimes using the load() method can be faster than the get() method.
18. What is difference between Hibernate save(), saveOrUpdate() and persist() methods?
- Hibernate save() method can be used to save entities to the database. The problem with the save() method is that it can be invoked without a transaction and if we have mapping entities, then only the primary object gets saved causing data inconsistencies. Also, save returns the generated id immediately.
- Hibernate persist() method is similar to the save() method with a transaction. It’s better to use persist() method than the save() method because we can’t use it outside the boundary of a transaction, so all the object mappings are preserved. Also, persist() method doesn’t return the generated id immediately, so data persistence happens when needed.
- Hibernate saveOrUpdate() method results into insert or update queries based on the provided data. If the data is present in the database, the update query is executed. We can use saveOrUpdate() without transaction also, but again you will face the issues with mapped objects not getting saved if a session is not flushed.
19. Why we should not Make an Entity Class final?
20. What is HQL and What are its Benefits?
21. What is Named Query in Hibernate?
- Fail fast: Their syntax is checked when the session factory is created, making the application fail fast in case of an error.
- Reusable: They can be accessed and used from several places which increases re-usability.
@NamedQuery(
name="findAllCustomersWithName",
query="SELECT c FROM Customer c WHERE c.name LIKE :custName"
)
22. What are the benefits of Named SQL Query?
23. What is Cascading and What Are Different Types of Cascading?
- ALL - cascades all entity state transitions
- PERSIST - cascades the entity persist operation.
- MERGE - cascades the entity merge operation.
- REMOVE - cascades the entity remove operation.
- REFRESH - cascades the entity refresh operation.
- DETACH - cascades the entity detach operation.
- SAVE_UPDATE - cascades the entity saveOrUpdate operation.
- REPLICATE - cascades the entity replicate operation.
- LOCK - cascades the entity lock operation.
@Entity
public class Person {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
private List < Phone > phones = new ArrayList < > ();
//Getters and setters are omitted for brevity
public void addPhone(Phone phone) {
this.phones.add(phone);
phone.setOwner(this);
}
}
@Entity
public class Phone {
@Id
private Long id;
@Column(name = "`number`")
private String number;
@ManyToOne(fetch = FetchType.LAZY)
private Person owner;
//Getters and setters are omitted for brevity
}
24. What are Design Patterns used in Hibernate framework?
Read more in detail at https://ramesh-java-design-patterns.blogspot.com/2018/04/design-patterns-used-in-hibernate.html
25. What are the different types of caches available in Hibernate?
- Session Cache - The session cache caches objects within the current session. It is enabled by default in Hibernate. Objects in the session cache reside in the same memory location.
- Second Level Cache - The second level cache is responsible for caching objects across sessions. When this is turned on, objects will first be searched in the cache and if they are not found, a database query will be fired. The second-level cache will be used when the objects are loaded using their primary key. This includes fetching of associations. Second-level cache objects are constructed and reside in different memory locations. The second-level cache is required to be configured with external cache provider like EhCache.
- Query Cache - Query Cache is used to cache the results of a query. When the query cache is turned on, the results of the query are stored against the combination query and parameters. Every time the query is fired the cache manager checks for the combination of parameters and query. If the results are found in the cache, they are returned, otherwise, a database transaction is initiated.
26. What are the Different States in Hibernate?
- transient - New objects created in the Java program but not associated with any hibernate Session are said to be in the transient state.
- persistent - An object which is associated with a Hibernate session is called a Persistent object. While an object which was earlier associated with Hibernate session but currently it's not associated is known as a detached object. You can call the save() or persist() method to store those objects into the database and bring them into the Persistent state.
- detached - You can re-attach a detached object to hibernate sessions by calling either update() or saveOrUpdate() method.
27. Name JPA Annotations?
28. Name Hibernate Annotations?
29. Explain Hibernate/JPA Primary key Generation Strategies?
1. GenerationType.AUTO - The GenerationType.AUTO is the default generation type and lets the persistence provider choose the generation strategy.
2. GenerationType.IDENTITY - The GenerationType.IDENTITY is the easiest to use but not the best one from a performance point of view.
3. GenerationType.SEQUENCE - The GenerationType.SEQUENCE is to generates primary key values and uses a database sequence to generate unique values.
4. GenerationType.TABLE - The GenerationType.TABLE gets only rarely used nowadays. It simulates a sequence by storing and updating its current value in a database table which requires the use of pessimistic locks which put all transactions into sequential order.
30. Which are the Different Types of Relationships Available in Hibernate Mapping?
One to One Mapping
One to Many Mapping
It represents the ONE-TO-MANY relationships between two tables. The one-to-many mapping means that one row in a table is mapped to multiple rows in another table.Many to One Mapping
Many to Many Mapping
It represents the many to many relationships between two tables.31. What is the Difference Between JPA and Hibernate?
You can learn Hibernate framework from end-to-end at Hibernate ORM 5 Tutorials
You can learn Java Persistence API at Java Persistence API
Comments
Post a Comment
Leave Comment