What is Hibernate Framework?
Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is java based ORM tool that provides framework for mapping application domain objects to the relational database tables and vice versa.
Hibernate provides reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use Hibernate persistence API for CRUD operations. Hibernate framework provide option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration.
Similarly hibernate configurations are flexible and can be done from XML configuration file as well as programmatically. For a quick overview of hibernate framework usage, you can go through Hibernate Beginners Tutorial.
What is Java Persistence API (JPA)?
Java Persistence API (JPA) provides specification for managing the relational data in applications. Current JPA version 2.1 was started in July 2011 as JSR 338. JPA 2.1 was approved as final on 22 May 2013.
What are the important benefits of using Hibernate Framework?
Some of the important benefits of using hibernate framework are:
Hibernate 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, that makes our code implementation independent.
Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism and association.
Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because learning curve is small and there are tons of online documentations and help is easily available in forums.
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 perform actual database queries only when it’s required.
Hibernate cache helps us in getting better performance.
For database vendor specific feature, hibernate is suitable because we can also execute native sql queries.
Overall hibernate is the best choice in current market for ORM tool, it contains all the features that you will ever need in an ORM tool.
What are the advantages of Hibernate over JDBC?
Some of the important advantages of Hibernate framework over JDBC are:
Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks more 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 transaction. In JDBC API, we need to write code for transaction management using commit and rollback. Read more at JDBC Transaction Management.
JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-catch block code. Most of the times it’s redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throw 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 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 provide 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 connection pool. This is very important feature in enterprise application and completely missing in JDBC API.
Hibernate supports JPA annotations, so code is independent of implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.
Name some important interfaces of Hibernate framework?
Some of the important interfaces of Hibernate framework are:
SessionFactory (org.hibernate.SessionFactory): SessionFactory is an immutable thread-safe cache of compiled mappings for a single database. We need to initialize SessionFactory once and then we can cache and reuse it. SessionFactory instance is used to get the Session objects for database operations.
Session (org.hibernate.Session): Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps JDBC java.sql.Connection and works as a factory for org.hibernate.Transaction. We should open session only when it’s required and close it as soon as we are done using it. Session object is the interface between java application code and hibernate framework and provide methods for CRUD operations.
Transaction (org.hibernate.Transaction): Transaction is a single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC or JTA transaction. Aorg.hibernate.Session might span multiple org.hibernate.Transaction in some cases.
What is hibernate configuration file?
Hibernate configuration file contains database specific configurations and used to initialize SessionFactory. We provide database credentials or JNDI resource information in the hibernate configuration xml file. Some other important parts of hibernate configuration file is Dialect information, so that hibernate knows the database type and mapping file or class details.
What is hibernate mapping file?
Hibernate mapping file is used to define the entity bean fields and database table column mappings. We know that JPA annotations can be used for mapping but sometimes XML mapping file comes handy when we are using third party classes and we can’t use annotations.
What is criteria API?
Criteria is a simple yet powerful API of hibernate which is used to retrieve entities through criteria object composition.
What are the benefits of using Hibernate template?
Following are some key benefits of using Hibernate template:
- Session closing is automated.
- Interaction with hibernate session is simplified.
- Exception handling is automated.
What are the two types of collections in hibernate?
Following are the two types of collections in hibernate:
- Sorted Collection
- Order Collection
What’s the difference between session.save() and session.saveOrUpdate() methods in hibernate?
Sessionsave() method saves a record only if it’s unique with respect to its primary key and will fail to insert if primary key already exists in the table.
saveOrUpdate() method inserts a new record if primary key is unique and will update an existing record if primary key exists in the table already.
What the benefits are of hibernate over JDBC?
- Hibernate can be used seamlessly with any type of database as its database independent while in case of JDBC, developer has to write database specific queries.
- Using hibernate, developer doesn’t need to be an expert of writing complex queries as HQL simplifies query writing process while in case of JDBC, its job of developer to write and tune queries.
- In case of hibernate, there is no need to create connection pools as hibernate does all connection handling automatically while in case of JDBC, connection pools need to be created.
How can we get hibernate statistics?
We can get hibernate statistics using getStatistics() method of SessionFactory class as shown below:
SessionFactory.getStatistics()
What is transient instance state in Hibernate?
If an instance is not associated with any persistent context and also, it has never been associated with any persistent context, then it’s said to be in transient state.
How can we reduce database write action times in Hibernate?
Hibernate provides dirty checking feature which can be used to reduce database write times. Dirty checking feature of hibernate updates only those fields which require a change while keeps others unchanged.
What’s the usage of callback interfaces in hibernate?
Callback interfaces of hibernate are useful in receiving event notifications from objects. For example, when an object is loaded or deleted, an event is generated and notification is sent using callback interfaces.
When an instance goes in detached state in hibernate?
When an instance was earlier associated with some persistent context (e.g. a table) and is no longer associated, it’s called to be in detached state.
What the four ORM levels are in hibernate?
Following are the four ORM levels in hibernate:
- Pure Relational
- Light Object Mapping
- Medium Object Mapping
- Full Object Mapping
What are different ways to disable hibernate second level cache?
Hibernate second level cache can be disabled using any of the following ways:
- By setting use_second_level_cache as false.
- By using CACHEMODE.IGNORE
- Using cache provider as org.hibernate.cache.NoCacheProvider
What is ORM metadata?
All the mapping between classes and tables, properties and columns, Java types and SQL types etc is defined in ORM metadata.
Which one is the default transaction factory in hibernate?
With hibernate 3.2, default transaction factory is JDBCTransactionFactory.
What’s the role of JMX in hibernate?
Java Applications and components are managed in hibernate by a standard API called JMX API. JMX provides tools for development of efficient and robust distributed, web based solutions.
How can we bind hibernate session factory to JNDI ?
Hibernate session factory can be bound to JNDI by making configuration changes in hibernate.cfg file.
In how many ways objects can be identified in Hibernate?
Object identification can be done in hibernate in following three ways:
- Using Object Identity: Using == operator.
- Using Object Equality: Using equals() method.
c. Using database identity: Relational database objects can be identified if they represent same row.