Introduction to Hibernate:


Hibernate was started in 2001 by Gavin King with colleagues from Cirrus Technologies.
Its main goal was to provide better persistence capabilities from EJB2 by simplifying the complexities. Following data contains a few details or FAQs about the hibernate concepts which are further to be used.

What is Hibernate?
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files. Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks. Hibernate simplifies:
1. Saving and retrieving your domain objects
2. Making database column and table name changes
3. Centralizing pre save and post retrieve logic
4. Complex joins for retrieving related items
5. Schema creation from object model.
So, Hibernate is simple ORM (Object Relational Mapping) tools that provides a framework for mapping an object-oriented domain model to a relational database.

What is ORM?
Actually ORM is complete MVC (Model View and Control) based application.

ORM tool:
• Hibernate Distributions
• Connectivity code
     1) Database Independent
     2) Lightweight Database connection
     3) Removes Dependencies
          • Expertise
          • Server
     4) Removes of Reimplementation
     5) Global Database Connectivity

xml : Keeps all objects in live mode.

MVC is divided into three parts :-
1. View: It is Presentation module
2. Control: It contains Servlet, which acts as controller
3. Model: Hibernate contribute in model part. Model part is also divided into three part:

I. Business Logic
II. DAO
III. Services.
Hibernate works on DAO (Data access Objects).

Why hibernate comes under the DAO?
Because DAO has ability to interact with the database i.e. JDBC (Java Database Connectivity) it provides specific data operations without exposing details of the database.

What are the benefits of Hibernate over JDBC?
1. Hibernate is database independent while in case of JDBC, developer has to write database specific queries.
2. In case of 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.
3. In Hibernate, Criteria Query takes care of Query Tuning. In case of JDBC you need to tune your queries.
4. No need to create any connection pool in case of Hibernate. You can use c3p0. In case of JDBC you need to write your own connection pool.
5. Automatic primary key generation.
6. Performance benefits like Lazy initialization, Outer join fetching, Batch fetching.

In short following are its advantages.
Advantages of Hibernate:
I. Auto DDL (Data Definition Language) Command: DDL query means Create Table, Alter Table, Rename Table. Hibernate automatically create table.
II. Support database independent query: Hibernate support database independent query language i.e. HQL (Hibernate Query Language).
III. Cache Support: cache actually stores the data already loaded from the database.
IV. Generator Support: Provide the facility to create primary key, foreign key, sequence generator.
V. Data Validation Support: Hibernate validation is recommended validation. Hibernate filter the data if data is valid then it send to database.
VI. Hibernate code is Exception free.
VII. ORM Relationalship support: Is like IS-A, HAS-A Relation .

Different saving methods in Hibernate
saveOrUpdate: Based on some checks it  calls either save or update. E.g. if no identifier exists, save is called. Otherwise update is called.
save: It will Persist an entity and will assign an identifier if one doesn't exist. If one does, it's essentially doing an update and returns the generated ID of the entity.
update: It will persist the entity using an existing identifier. If no identifier exists, then an exception is thrown.
merge: Hibernate has following three Object states-

Transient, Detached and Persistent. Object states, with save & update, then one is dealing with persistent objects. They are linked to a Session so Hibernate knows what has changed. But when you have a transient object, there is no session involved. In these cases merge is to be used for updates and persist for saving. For persist, as mentioned above, this is used on transient objects. It does not return the generated ID.

What are the Core interfaces of Hibernate framework??
The five core interfaces are used in just about every Hibernate application. Using these interfaces, one an store and retrieve persistent objects and control transactions.
1. Session interface
2. SessionFactory interface
3. Transaction interface
4. Query and Criteria interfaces

What are the three Types Hibernate Object States?
Transient- Newly created object so not associated with any Session and database.
Persistent - Associated with a unique Session
Detached - Previously persistent, not associated with any Session.

What is lazy loading in Hibernate??
Lazy-loading can help improve the performance significantly since often you won't need the children and so they will not be loaded. If you have a parent and that parent has a collection of children. Hibernate now can "lazy-load" the children, which means that it does not actually load all the children when loading the parent. Instead, it loads them when requested to do so. You can either request this explicitly or, and this is far more common, hibernate will load them automatically when you try to access a child.

Define HibernateTemplate
HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked Hibernate Exceptions into unchecked DataAccessExceptions. It automatically opens and closes sessions and commit or rollback transactions after your code executed.

What are the Collection types in Hibernate?
Following are collection types used in Hibernate.
1. Array
2. Map
3. Bag
4. Set
5. List

What is Session?
Session is a light weight and a non-thread safe and main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. You can use like this
SessionFactory sessionFactory = new Configuration ().configure ().buildSessionFactory ();
Session session = sessionFactory.openSession ();

What is a SessionFactory?
SessionFactory Interface is used to create session instances in hibernate. Usually an application has a single SessionFactory instance. SessionFactory is thread safe.

What is transient Object in Hibernate?
If persistent class is just instantiated using the new operator which is not associated with a Session. No persistent representation in the database and no identifier value have been assigned to an object. And it will be destroyed by the garbage collector if the application does not hold a reference anymore. This kind of object is called transient Object. Example:
Student studentObj = new Student ();
studentObj.setName("Kumar");
studentObj- transient object.

What is HQL?
HibernateQuery Language is a powerful query language its syntax is quite similar to database SQL language,compared with SQL, however, HQL is fully object-oriented and understands notions like inheritance, polymorphism and association.
HQL Select Query Example:
Query query = session.createQuery("from Student where studentName = 'suresh ");

What is POJO?
POJO(Plain Old Java Object) is a javabean that have defined setter and getter methods for all properties. Decoupling the application code from the infrastructure frameworks is one of the many benefits of using POJOs. They also simplify development because rather than being forced to think about everything- business logic, persistence, transactions, etc.

What the four ORM levels are in hibernate?
Following are the four ORM levels in hibernate:
1. Pure Relational
2. Light Object Mapping
3. Medium Object Mapping
4. Full Object Mapping

How to re-attach detached objects in hibernate?
Detached objects can be reattached by calling "session.merge()" method of session class.

What is the difference between load() and get() method in hibernate?
If you are sure that the object exists then use load() else use get() methods. load() method will throw an exception if the unique id is not found in the database but get() method will return null if the unique id is not found in the database.

What is the difference between detached state and transient state Objects?
Transient objects do not have association with the databases and session objects but detached objects have corresponding entries in the database. These are persistent and not connected to the Session object. These objects have the synchronized data with the database when the session was closed. Version property is used in hibernate to know whether an object is in transient state or in detached state.

What is the difference between the session.update() method and the session.lock() method? The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object otherwise use session.update().

What are the different fetching strategy in Hibernate?
Join fetching: Using an OUTER JOIN hibernate retrieves the associated instance or collection in the same SELECT.
Select fetching: a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you access the association.
Subselect fetching: a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifyinglazy="false", this second select will only be executed when you access the association.
Batch fetching: It is an optimization strategy for select fetching.Using primary or foreign keys hibernate retrieves a batch of entity instances or collections in a single SELECT. Find the more info about Fetching strategies here.