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.
What is Java Persistence API (JPA)?
Java Persistence API (JPA) provides specification for managing the relational data in applications.
JPA specifications is defined with annotations in javax.persistence package. Using JPA annotation helps us in writing implementation independent code.
What are the important benefits of using Hibernate Framework?
Some of the important benefits of using hibernate framework are:
- Hibernate improved productivity by High-level object-oriented API, Less Java code to write, No SQL to write,
- Hibernate improved performance by Sophisticated caching, Lazy loading and Eager loading
- 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.
- Hibernate improved maintainability by a lot less code to write.
- Hibernate improved portability by generating database-specific SQL for you
Hibernate contains all the features that you will ever need in an ORM tool.
What is the difference between hibernate and jdbc ?
- Hibernate supports inheritance, associations and collections. These features are not present with JDBC API.
- Hibernate implicitly provides transaction management, 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.
- 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.
Why hibernate and how does it help in the programming?
The main advantage of Hibernate (ORM) framework is that it shields developer to write a messy SQL. Apart from that ORM provides following benefits.
- Improve Productivity of the developer by providing high level object oriented API (e.g. API for easily maintaining the connection to data base, mapping java classes to relational database tables), less java code to write, helps to avoid writing SQL query.
- Improved performance by providing sophisticated caching, lazy loading and eager loading features.
- Provide portability, the framework helps to generate database specific SQL for you.
What are the Core interfaces of Hibernate framework?
Some of the Core 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. A org.hibernate.Session might span multiple org.hibernate.Transaction in some cases.
Configuration (org.hibernate.cfg.Configuration): An instance of
org.hibernate.cfg.Configurationrepresents an entire set of mappings of an application’s Java types to an SQL database. The org.hibernate.cfg.Configuration is used to build an immutable
org.hibernate.SessionFactory. The mappings are compiled from various XML mapping files.
Query and Criteria: The
org.hibernate.Criteriainterface defines several methods for creating
Queryobjects programmatically. We generally use a Session object to call the createCriteria() method and create a Criteria object
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 Hibernate SessionFactory?
SessionFactory is the factory class used to get the Session objects. SessionFactory is responsible to read the hibernate configuration parameters and connect to the database and provide Session objects. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.
The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.
SessionFactory also provide methods to get the Class metadata and Statistics instance to get the stats of query executions, second level cache details etc.
What is Hibernate Session?
Hibernate Session is the interface between java application layer and hibernate. This is the core interface used to perform database operations. Lifecycle of a session is bound by the beginning and end of a transaction.
Session provide methods to perform create, read, update and delete operations for a persistent object. We can execute HQL queries, SQL native queries and create criteria using Session object.
What are POJOs and what’s their significance?
POJOs( Plain Old Java Objects) are java beans with proper getter and setter methods for each and every properties.
Use of POJOs instead of simple java classes results in an efficient and well constructed code.
HQL is the query language used in Hibernate which is an extension of SQL. HQL is very efficient, simple and flexible query language to do various type of operations on relational database without writing complex database queries.
What is difference between openSession and getCurrentSession?
Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file. Since this session object belongs to the hibernate context, we don’t need to close it. Once the session factory is closed, this session object gets closed.
Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment.
There is another method openStatelessSession() that returns stateless session.
What is criteria API?
Criteria is a simple yet powerful API of hibernate which is used to retrieve entities through criteria object composition.
What is difference between Hibernate Session get() and load() method?
Hibernate session comes with different methods to load data from database. get and load are most used methods.
- get() loads the data as soon as it’s called whereas load() returns a proxy object and loads data only when it’s actually required, so load() is better because it support lazy loading.
- load() throws exception when data is not found, we should use it only when we know data exists.
- We should use get() when we want to make sure data exists in the database.
What’s the difference between session.save() and session.saveOrUpdate() methods in hibernate?
save() 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 are the different types of caches in Hibernate?
Hibernate uses two different type of caches for objects: first-level cache and second-level cache. First level of cache is associated with Session object, while second-level of cache is associated with the SessionFactory object. By default, Hibernate uses first-level of cache on a per-transaction basis. Hibernate mainly use this cache to reduce the number of SQL queries it needs to generate within a given transaction.
What is hibernate caching? Explain Hibernate first level cache?
hibernate caches query data to make our application faster. Hibernate Cache can be very useful in gaining fast application performance if used correctly. The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application.
Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely.
Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.
What is lazy fetching in Hibernate?
In Hibernate Lazy fetching is associated with child objects loading for its parents. Through Hibernate mapping file (.hbm.xml) you can specified the selection of loading child objects. By default Hibernate does not load child objects. Lazy=rue means not to load the child objects.
What is the difference between merge and update method?
Use update() method when you are sure that session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.
What are different states of an entity bean?
An entity bean instance can exist is one of the three states.
Transient: When an object is never persisted or associated with any session, it’s in transient state. Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete().
Persistent: When an object is associated with a unique session, it’s in persistent state. Any instance returned by a get() or load() method is persistent.
Detached: When an object is previously persistent but not associated with any session, it’s in detached state. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().
What are the collection types in Hibernate?
There are five collection types in hibernate used for one-to-many relationship mappings.
How to implement Joins in Hibernate?
There are various ways to implement joins in hibernate.
- Using associations such as one-to-one, one-to-many etc.
- Using JOIN in the HQL query. There is another form “join fetch” to load associated data simultaneously, no lazy loading.
- We can fire native sql query and use join keyword.
What is Named SQL Query?
Hibernate provides Named Query that we can define at a central location and use them anywhere in the code. We can created named queries for both HQL and Native SQL.
Hibernate Named Queries can be defined in Hibernate mapping files or through the use of JPA annotations
How to show hibernate generated sql queries in log files?
We can set below property for hibernate configuration to log SQL queries.
However we should use it only in Development or Testing environment and turn it off in production environment.
What is Hibernate Proxy and how it helps in lazy loading?
Hibernate uses proxy object to support lazy loading. Basically when you load data from tables, hibernate doesn’t load all the mapped objects. As soon as you reference a child or lookup object via getter methods, if the linked entity is not in the session cache, then the proxy code will go to the database and load the linked object. It uses javassist to effectively and dynamically generate sub-classed implementations of your entity objects.
What is cascading and what are different types of cascading?
When we have relationship between entities, then we need to define how the different operations will affect the other entity. This is done by cascading and there are different types of it.
Note that Hibernate CascadeType enum constants are little bit different from JPA javax.persistence.CascadeType, so we need to use the Hibernate CascadeType and Cascade annotations for mappings, as shown in above example.
Commonly used cascading types as defined in CascadeType enum are:
None: No Cascading, it’s not a type but when we don’t define any cascading then no operations in parent affects the child.
ALL: Cascades save, delete, update, evict, lock, replicate, merge, persist. Basically everything
SAVE_UPDATE: Cascades save and update, available only in hibernate.
DELETE: Corresponds to the Hibernate native DELETE action, only in hibernate.
DETATCH, MERGE, PERSIST, REFRESH and REMOVE – for similar operations
LOCK: Corresponds to the Hibernate native LOCK action.
REPLICATE: Corresponds to the Hibernate native REPLICATE action.
What is HibernateTemplate class?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.
When Spring and Hibernate integration started, Spring ORM provided two helper classes – HibernateDaoSupport and HibernateTemplate. The reason to use them was to get the Session from Hibernate and get the benefit of Spring transaction management.
Please note from Hibernate 3.0.1, We can use
SessionFactory getCurrentSession() method to get the current session and use it to get the spring transaction management benefits.
One other benefit of
HibernateTemplate was exception translation but that can be achieved easily by using
@Repository annotation with service classes.
What is Hibernate SQL Dilect?
Dialect means “the variant of a language”. Hibernate, as we know, is database agnostic. It can work with different databases. However, databases have proprietary extensions/native SQL variations, and set/sub-set of SQL standard implementations. Therefore at some point hibernate has to use database specific SQL. Hibernate uses “dialect” configuration to know which database you are using so that it can switch to the database specific SQL generator code whenever necessary.
What is the difference between sorted and ordered collection in hibernate?
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator.
If your collection is not large, it will be more efficient way to sort it.
Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is very large, it will be more efficient way to sort it .
How can a whole class be mapped as immutable?
Mark the class as mutable=”false” (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.
What do you mean by fetching strategy ?
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.
What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.
What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:
- Table per class hierarchy
- Table per subclass
- Table per concrete class
What is the default cache service of hibernate?
Hibernate supports multiple cache services like EHCache, OSCache, SWARMCache and TreeCache and default cache service of hibernate is EHCache.
In how many ways, objects can be fetched from database in hibernate?
Hibernate provides following four ways to fetch objects from database:
- Using HQL
- Using identifier
- Using Criteria API
- Using Standard SQL
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’s the use of session.lock() in hibernate?
session.lock() method of session class is used to reattach an object which has been detached earlier. This method of reattaching doesn’t check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.
How can we map the classes as immutable?
If we don’t want an application to update or delete objects of a class in hibernate, we can make the class as immutable by setting mutable=false
What design patterns are used in Hibernate framework?
Some of the design patterns used in Hibernate Framework are:
Domain Model Pattern – An object model of the domain that incorporates both behavior and data.
Data Mapper – A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself.
Proxy Pattern : for lazy loading
Factory pattern : in SessionFactory
What is Hibernate Validator Framework?
Hibernate validator framework is the implementation of JSR303 and JSR349 provides specification for validating a bean by using annotations. Hibernate Validator provides the reference implementation of both these bean validation specification.
What is hibernate n+1 problem
Hibernate n+1 problems comes for one to many relationship when we do not use right fetch strategy, In case of N+1 Problem the hibernate may have to run the Query N time to get the attached oneToMany Object for setting it with the main Entity.
What is the Difference between JPA and Hibernate
JPA is just guidelines to implement the Object Relational Mapping (ORM) and there is no underlying code for the implementation.
Where as, Hibernate is the actual implementation of JPA guidelines. When hibernate implements the JPA specification, this will be certified by the JPA group upon following all the standards mentioned in the specification. For example, JPA guidelines would provide information of mandatory and optional features to be implemented as part of the JPA implementation.