Hibernate Tutorial

Hibernate framework simplifies the development of java application to interact with the database. Hibernate is an open source, lightweight, ORM (Object Relational Mapping) tool.


1.Advantages of Hibernate Framework


There are many advantages of Hibernate Framework. They are as follows:


1) Opensource and Lightweight: Hibernate framework is opensource under the LGPL license and lightweight.


2) Fast performance: The performance of hibernate framework is fast because cache is internally used in hibernate framework. There are two types of cache in hibernate framework first level cache and second level cache. First level cache is enabled bydefault.
   (I).First Level Cache: Session object holds the first level cache data. It is enabled by default. The first level cache data will not be available to entire application. An application can use many session object.


(ii)Second Level Cache : SessionFactory object holds the second level cache data. The data stored in the second level cache will be available to entire application.


3) Database Independent query: HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the database independent queries. So you don't need to write database specific queries. Before Hibernate, If database is changed for the project, we need to change the SQL query as well that leads to the maintenance problem.


4) Automatic table creation: Hibernate framework provides the facility to create the tables of the database automatically. So there is no need to create tables in the database manually.


5) Simplifies complex join: To fetch data form multiple tables is easy in hibernate framework.


6) Provides query statistics and database status: It supports Query cache and provide statistics about query and database status.

2.Hibernate Architecture
4 layers in hibernate architecture java Application layer, hibernate framework layer, backhand api layer and database layer











Hibernate framework uses many objects session factory, session, transaction etc. alongwith existing Java API such as JDBC (Java Database Connectivity), JTA (Java Transaction API) and JNDI (Java Naming Directory Interface).
(i)SessionFactory:
The SessionFactory is a factory of session and client of ConnectionProvider. It holds second level cache (optional Applciation) data. The org.hibernate.SessionFactory interface provides factory method to get the object of Session.


(ii)Session
The session object provides an interface between the application and data stored in the database. It is a short-lived object and wraps the JDBC connection. It is factory of Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. The org.hibernate.Session interface provides methods to insert, update and delete the object. It also provides factory methods for Transaction, Query and Criteria.


(iii).Transaction
The transaction object specifies the atomic unit of work. The org.hibernate.Transaction interface provides methods for transaction


(iv)ConnectionProvider:It is a factory of JDBC connections. It abstracts the application from DriverManager or DataSource. ptional.


(v).TransactionFactoryIt is a factory of Transaction. It is optional.
3.Steps to Create Hibernate Application




In Hibernate Mapping File(emp.hbm.xml)
1.id : It is the subelement of class. It specifies the primary key attribute in the class.
2.generator: It is the subelement of id. It is used to generate the primary key. There are many generator classes such as assigned (It is used if id is specified by the user), increment, hilo, sequence, native etc. We will learn all the generator classes later.
4.Hibernate with Annotation


The core advantage of using hibernate annotation is that you don't need to create mapping (hbm) file. Here, hibernate annotations are used to provide the meta data.


All the JPA annotations are defined in the javax.persistence.* package. Hibernate EntityManager implements the interfaces and life cycle defined by the JPA specification.


@Entity : annotation marks this class as an entity.
@Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name bydefault.Both @Entity,@Table are at the Top of the class.


@Id annotation marks the identifier for this entity.
@Column annotation specifies the details of the column for this property or field. If @Column annotation is not specified, property name will be used as the column name bydefault.


The only changes with Above Application is
  • we dont has hbm.xml. So mapping done in Beanclass it self by using annotations
  • in hibernate.cfg.xml, previous we decalred <mappling res=”file.xml”> but now we give <mapping class=”bean”>
  • In Percistace class we use configuration = new new AnnotationConfiguration(); and configure() without cfg.file.
Reamiang all are same.







5.Generator classes in Hibernate
The <generator> subelement of id used to generate the unique identifier for the objects of persistent class
All the generator classes implements the org.hibernate.id.IdentifierGenerator interface. The application programmer may create one's own generator classes by implementing the IdentifierGenerator interface


  1. assigned: It is Default Generator. Works with all databases. It identifies the Field values given by user & sets those values
  2. increment :This algorithm uses maximum value+1 and generates identity values of type long, short or int.
It does not consider the deleted record values while generating identity value Works with all databases
  1. identity  : uses Maximum value+1.it take deleted value consider..not for ORACLE
  2. sequence:It uses the sequence of the database. if there is no sequence defined, it creates a sequence automatically
  3. hilo   : It uses high and low algorithm to generate the id of type short, int and long;Ex: (max-low=hilo)
  4. seqhilo  : It uses high and low algorithm on the specified sequence name. The returned id is of type short, int or long.
  5. Native: It uses identity, sequence or hilo depending on the database vendor.
  6. uuid  : This algorithm uses id address of current computer as base to generate identity value
  7. guid : Uses the Database generated GUID based String as identity values. This algorithm works only with SQL server.
  8. Select : It uses the primary key returned by the database trigger
  9. foreign : It uses the id of another associated object, mostly used with <one-to-one> association.
  10. Sequence-identity : It uses a special sequence generation strategy. It is supported in Oracle 10g drivers only
6.SQL Dialects in Hibernate
                                                                      It converts Hibernate Qry to Specific Database Query
For connecting any hibernate application with the database, you must specify the SQL dialects. There are many Dialects classes defined for RDBMS in the org.hibernate.dialect package. They are as follows:

7.Hibernate Inheritance Mapping


We can map the inheritance hierarchy classes with the table of the database. There are three inheritance mappings the hibernate:


  1. Table Per Hierarchy:
In table per hierarchy mapping, single table is required to map the whole hierarchy, an extra column (known as discriminator column) is added to identify the class. But nullable values are stored in the table .
  1. Table Per Concrete class
In this tables are created as per class. But duplicate column is added in subclass tables.
  1. Table Per Subclass
In this strategy, tables are created as per class but related by foreign key. So there are no duplicate columns.




1.Table Per Hierarchy:


Here one Table is Divided in to no.of classes(one main class which contain ID as Primary, & Remaining are sub-classes with other cols)
Here Table Core columns(Like ID,name) are placed in MainBean (EmpBean.java).
Reaming columns are placed in sub-classes and the subclasses must Extends MainBean(RegEmp extends EmpBean)
we have a discriminator column, it says which class data is inserted in particular row. discriminator column is one of the column of our table
we have to declare discriminator column in hibernate mapping file with <discriminator column="type" type="string"/>
in hbm.xml we have to configure our MainBean with discriminator-value="emp"
and subclasses are configure with their column properties with <subclass name="RegEmpBean" discriminator-value="reg_emp">
Each sub class must contain discriminator-value="reg_emp" property. <subclass> in between of <class> tag
In percistace Class if u use MainBean it gives only that class colums to Store. But we create with SubBean it gives MianBean colmns also

Table Per Hierarchy using Annotation
using annotation. You need to use
@Inheritance(strategy=InheritanceType.SINGLE_TABLE),
@DiscriminatorColumn
@DiscriminatorValue
annotations for mapping table per hierarchy strategy.

2.Table Per Concrete class
in  this if three tables have same propeties, but no way related to each other.you want join them.such cases known as TablePerConcrete



3.Table Per Subclass
so-far we dealing the table with no relation between them. But here we use the tables which are depends on others using foreign keys
we are going to use hb2ddl.auto property  as UPDATE in hibernate.cfg.xml to generate the table automatically. So we don't need to be worried about creating tables in the database.
  • Here MainBean has Primary key(Emp_Bean), and name propeties
  • Subbeans having forigen key of Emp_Bean primary key.so SubBeans Extends MianBean and gets the Propeties
  • in Mapping we use <joined-subclass name="Cont_Bean" table="tbs_con"> and <key name=”id”> for foreign key

8.Collection Mapping in Hibernate
We can map collection elements of Persistent class in Hibernate. You need to declare the type of collection in Persistent class from one of the following types:
  1. java.util.List
  2. java.util.Set
  3. java.util.SortedSet
  4. java.util.Map
  5. java.util.SortedMap
  6. java.util.Collection
  7. or write the implementation of org.hibernate.usertype.UserCollectionType


Ex: private List<String> answers;//List can be of any type  
There are many subelements of <class> elements to map the collection. They are <list>, <bag>, <set> and <map>
if collection stores entity reference (another class objects), we need to define <one-to-many> or <many-to-many> element.
Ex: private List<Answer> answers;//Here, List stores the objects of Answer class  


There are three subelements used in the list:


1.<key> :
Key element is used to define the foreign key in this table based on the Question class identifier.
The key element is used to define the foreign key in the joined table based on the original identity. The foreign key element is nullable by default. So for non-nullable foreign key, we need to specify  not-null attribute such as:

2.<index>
element is used to identify the type. List and Map are indexed collection. The collection elements are in two forms:


indexed : The List and Map collection are indexed. indexed collection means List and Map requires an additional element <index>.
Non-indexed :  set and bag collections are non-indexed
whereas. Here,


3.<element> is used to define the element of the collection.The collection elements can have value or entity reference (another class object). We can use one of the 4 elements
  • element
  • component-element
  • one-to-many, or
  • many-to-many
The element and component-element are used for normal value such as string, int etc. whereas one-to-many and many-to-many are used to map entity reference.


List and Map are index based collection, so an extra column will be created in the table for indexing.

9.Mapping List in Collection Mapping


(i)<element> mapping
List that stores string value not entity reference that is why are going to use element instead of one-to-many within the list element.
→ Here question(id,qname) and answer(qid,type,answer) are two tables. Here we use <elemnet> mapping.so no need of answer bean
→ in question Bean we declare answer as a list<String>, and we mention in xml with key,type,element.so no nedd of answer Bean
(ii)one-to-many Mapping
→ <one-to-many> mapping.so we need to deine both Answers and QuestionBean
→ in question Bean we declare answer as a list<Answer>, and we mention in xml with key,type,and<ont-to-many> mappings
→ And also configure AnswerBean in xml with their properties

10.Mapping Bag in Collection Mapping
1.element mapping
If our persistent class has List object, we can map the List by list or bag element in the mapping file. The bag is just like List but it doesn't require index element.
Here, we are using the scenario of Forum where one question has multiple answers.




2.ont-to-many Mapping
If the persistent class has list object that contains the entity reference, we need to use one-to-many association to map the list element. We can map this list object by either list or bag.Notice that bag is not index-based whereas list is index-based

11.Mapping Set in Collection Mapping


1.element mapping
If our persistent class has Set object, we can map the Set by set element in the mapping file. The set element doesn't require index element. The one difference between List and Set is that, it stores only unique values.






2.Set One to many


If the persistent class has set object that contains the entity reference, we need to use one-to-many association to map the set element. We can map this list object by either set.
It is non-index based and will not allow duplicate elements.


Let's see the persistent class that has set objects. In this case, there can be many answers for a question and each answer may have its own information that is why we have used set element to represent a collection of answers.



12.Component Mapping
In component mapping, we will map the dependent object as a component. An component is an object that is stored as an value rather than entity reference. This is mainly used if the dependent object doen't have primary key. It is used in case of composition (HAS-A relation), that is why it is termed as component. Let's see the class that have HAS-A relationship.
Here, address is a dependent object. Hibernate framework provides the facility to map the dependent object as a component. Let's see how can we map this dependent object in mapping file.
13.Hibernate Query Language (HQL) (java4s)
So far we done the operations on single object (single row), here we will see modifications, updates on multiple rows of data (multiple objects) at a time
  • HQL is the own query language of hibernate and it is used to perform bulk operations on hibernate programs
  • An object oriented form of SQL is called HQL
  • here we replace table column names  with POJO class variable names & table names with POJO class names


Advantages Of HQL:
  • HQL is database independent, means if we write any program using HQL, it wi;ll  execute in all the databases
  • HQL supports object oriented features like Inheritance, polymorphism, Associations(Relation ships)
  • HQL is initially given for selecting object from database and in hibernate 3.x we can do DML operations ( insert, update…) too

1.HQL Select


If we want to select a Complete Object from the database, we use POJO class reference in place of   *  
In this case (select a complete object from the database) we can directly start our HQL command from,  from key word
Example:



2.Procedure To Execute HQL Command


  • If we want to execute execute an HQL query on a database, we need to create a query object
  • ” Query ” is an interface given in org.hibernate package
  • In order to get query object, we need to call createQuery() method in the session Interface
  • we need to call list method for executing an HQL command on database, it returns java.util.List
  • we need to use java.util.Iterator for iterating the List collection








3.Different Ways Of Executing HQL


Case 1: [ Selecting Complete Object ]
In this approach, we are going to select complete object from the database, so while iterating the collection, we need to typecast each object into our  POJO class type only
Internally hibernate converts each row selected from the table into an object of POJO class and hibernate stores all these POJO class objects into list so while iterating the collection, we typecast into POJO class type


Case 2: [ Selecting Partial Object ]
In this approach we are going to select partial object, (selected columns, i mean more than one column not single column)
In this case hibernate internally stores the multiple column values of each row into an object array and stores these object arrays into List collection.At the time of iterating the collection, we need to typecast the result into an object arrays


Case 3: [ Selecting Partial Object ]
In this case we are going to select partial object with single column from the database
In this case hibernate internally creates an object of that value type and stores all these objects into the list collection
At the time of iterating the collection, we need to typecast into that object type only

1.Insert Query:
HQL supports only the INSERT INTO……… SELECT……… ; there is no chance to write INSERT INTO………..VALUES, i mean while writing the insert query, we need to select values from other table, we can’t insert our own values manually, you will understand by seeing the following example..


14.Hibernate Criteria Query
By HQL , you can't add ORDER BY, GROUP By Restrictions.But by Using Criteria Query we do those things


  • Criteria is only for selecting the data from the database, that to we can select complete objects only not partial objects
  • We cant perform non-select operations using this criteria
syntax:
Criteria crit = session.createCriteria(HQL.class/ ob);

  • If we want to put conditions to load data from database, using criteria then we need to create one Criterion Interface object and we need to add this object to Criteria Class object


  • In order to get Criterion object, we need to use Restrictions class
  • Restrictions is the factory for producing Criterion objects, but friends there is no explicit relation between Criterion interface and Restrictions class, it means Restrictions class is not implemented from Criterion Interface
  • In Restrictions class, we have all static methods and each method of this class returns Criterion object
  • Restrictions class is also given in “org.hibernate.criterion” package

15.Hibernate Projections


So far in criteria, we are able to load complete object.The projections concept is introduced in hibernate 3.0 and mainly we can do the following 2 operations using the projection
  • We can load partial object from the database
  • We can find the Result of Aggregate functions

Projection is an Interface given in “org.hibernate.criterion” package,
Projections is an class given in same package,  actually Projection is an interface, and Projections is an class and is a factory for producing projection objects.
In Projections class, we have all static methods and each method of this class returns Projection interface object.
If we want to add a Projection object to Criteria then we need to call a method setProjection()
Remember, while adding projection object to criteria, it is possible to add one object at a time.  It means if we add 2nd projection object then this 2nd one will overrides the first one (first one wont be work), so at a time we can only one projection object to criteria object.
Using criteria, if we want to load partial object from the database, then we need to create a projection object for property that is to be loaded from the database

16.Difference between HQL and Criteria Query in Hibernate


  1. HQL is to perform both select and non-select operations on the data,  but Criteria is only for selecting the data, we cannot perform non-select operations using criteria
  2. HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries
  3. HQL doesn’t support pagination concept, but we can achieve pagination with Criteria
  4. Criteria used to take more time to execute then HQL
  5. With Criteria we are safe with SQL Injection because of its dynamic query generation but in HQL as your queries are either fixed or parametrized, there is no safe from SQL Injection.


17.Native SQL


Native SQL means using the direct SQL command specific to the particular (current using) database and executing it with using hibernate


If we want to execute Native SQL Queries on the database then, we need to construct an object of SQLQuery, actually this SQLQuery is an interface extended from Query and it is given in ” org.hibernate package ”


In order to get an object of SQLQuery, we need to use a method createSQLQuery() given by session interface.


While executing native sql queries on the database, we use directly tables, column names directly in our command.


Remember, while executing Native SQL Queries, even though we are selecting complete objects from teh database we need to type cast into object array only, not into our pojo class type, because we are giving direct table, column names in the Native SQL Querie so it does’nt know our class name


If we execute the command, always first it will put’s data in ResultSet and from there List






while selecting data from the table, even though you are selecting the complete object from the table, in while loop still we type cast into object array only right


See the above code, we typecast into the object[] arrays right..,  in case if we want to type cast into our POJO class (i mean to get POJO class obj), then we need to go with entityQuery concept


In order to inform the hibernate that convert each row of ResultSet into an object of the POJO class back, we need to make the query as an entityQuery
to make the query as an entityQuery, we need to call addEntity() method





18.Hibernate Named Query


While executing either HQL, NativeSQL Queries if we want to execute the same queries for multiple times and in more than one client program application then we can use the Named Queries mechanism


In hibernate mapping file we need to configure a query by putting some name for it and in the client application, we need to use getNamedQuery() given by session interface, for getting the Query reference and we need to execute that query by calling list()







19.Hibernate Relationships In Depth


Using hibernate, if we want to put relationship between two entities [ objects of two pojo classes ], then in the database tables, there must exist foreign key relationship, we call it as Referential integrity.
Using hibernate we can put the following 4 types of relationships
One-To-One, Many-To-One, Many-To-Many, One-To-Many


1.Hibernate – One-To-One Example (http://www.mkyong.com/)
A one-to-one relationships occurs when one entity is related to exactly one occurrence in another entity
A one-to-one relationship table design, a STOCK table contains exactly one record in STOCK_DETAIL table. Both tables have the same Stock_Id as primary key. In STOCK_DETAIL table, Stock_Id is the primary key and also a foreign key to STOCK table. This is the common way of define “one-to-one” table relationship.
2.Hibernate – One-To-Many


A one-to-many relationship occurs when one entity is related to many occurrences in another entity.
This is a one-to-many relationship table design, a STOCK table has many occurrences STOCK_DAILY_RECORD table.








3.Hibernate – Many-To-Many


Many-to-many relationships occur when each record in an entity may have many linked records in another entity and vice-versa.


This is a many-to-many relationship table design, a STOCK table has more than one CATEGORY, and CATEGORY can belong to more than one STOCK, the relationship is linked with a third table called STOCK_CATEGORY.


Table STOCK_CATEGORY only consist of two primary keys, and also foreign key reference back to STOCK and CATEGORY.














1 Comments

Thank You

Previous Post Next Post