hibernate framework part 2 – vikramnvp11

Hi friends this is a Hibernate Framework Tutorial part 2. By the end of this post you will get link to part 1.

HQL (Hibernate Query Language)

hibernate query language
hibernate query language

It is a Query Language in which we write the queries based on class name and data member name                         

          Difference between HQL and SQL

HQL SQL
DB Independent DB Dependent
Object Model Relational Model

To Use HQL we need to follow 2 steps

a)Create the query

b)Process the result

a) Create the query

To Create a Query we use createQuery(), present in Session Object. Hence This method returns an Object Of Query.           

b) Process the result

To Process the Result we have 2 methods

a)uniqueResult

b)list

Both these methods are present in Query Object

a) uniqueResult

It is used when the query returns only one record, which returns an Object       

HQL doesn’t support select *  ?->placeholder

Disadvantages Of Placeholder: Developer has to remember the index of placeholders. We have to use appropriate setter methods.

To overcome these disadvantages we use “named parameter”

                                                Syntax: =:var_name

Named Query

In named Queries we write queries in DTO and process the result                

To use named Query we have to follow 2 steps

  •  Type the query in DTO
  •  Get the named query in the DAO class and process the result             

                Syntax: @NamedQuery(name,Query)

To get the namedQuery in DAO class

We have to use getNamedQuery(),present in Session Object which returns a Query Object        

Note: Only one SessionFactory for entire application.Hence Singleton Class should be used.      

To execute multiple namedQueries

We use:

@NamedQueries Annotation

                                                @NamedQueries({@NamedQuery(),@NamedQuery()})

ex:@NamedQueries({@NamedQuery(name=”getByDuration”,query=”from GameDTO where duration=:duration”), @NamedQuery(name=”getByName”,query=”from GameDTO where gameName=:name”)})                  

Update a record using HQL

There are 2 steps

a) Create a Query

b) Execute the Query using executeUpdate()

String HQL=”update GameDTO set duration=120″+”where gameName=:name”;

create a query
create a query

To Delete the record:

@NamedQuery(name=”delete”,query=”Delete from GameDTO where gameName=:name”)

Note:  To avoid “NullPointerException” use list().                                             

POR(Problem Of relation)

Mapping Has-A relationship to database. To provide solution for POR, Hibernate has provided 4 strategies

                                a) One-to-One

                                b) One-to-many

                                c) Many-to-one

                                d) Many-to-many

a) One-to-One:

In One to One relationship one class will have reference of another class only once.

Steps to create a one to one DAO:

1.Create an object of owning entity and populate the values.

2.Create an object of associated entity and populate the values.

3.Relate owning entity with the associated entity using setter method.

4.Use save() to save owning entity to the database.       

Cascade

Cascade is used to specify the operations that should be performed on associative entity. The value for cascade is enum type i.e., cascade type

@oneToOne(cascade=CascadeType.ALL)

                                                Cascade type has constants like ALL, DETACH, MERGE, PERSIST, REFRESH, REMOVE                         

In one-one bi direction,when we use joinColumn, an extra column is created and values for previous record will be null. Hence to avoid null we use @primaryKeyJoinColumn

Lazy Loading

Using Lazy loading we can control the objects that should be loaded from the database. To configure lazy loading we have to use an enum called as FetchType

FetchType has 2 constants

a)Lazy

b)Eager

If we doesn’t specify the FetchType by default it is always eager Fetching

Note: Whenever we load owner table associate table is also loaded causing unnecessary load on database and 200 objects unnecessary load on heap memory. Thus by using LAZY control the objects during fetching.

2. One-to-Many:

One class is having multiple references to another class.

Steps to create onetomanyDAO:

  • Create an object of owning entity.
  • Make Multiple objects of associated entity.
  • Create a Collection of associated entities. (Here we use list and no set because it has compareTO method and hence time taken is more)
  • Relate owning entity with the collection of associated entities.
  • Use save() to save owning entity.

Note: If no @JoinColumn in One-to-Many then there will be three tables in the database.

3. Many-to-One:

Many-to-One relationship is bi direction of one-to-many. At compile time Many-to-One is same as One-to-One relationship.

Steps to create Many-to-One relationship:

                                1.Create multiple objects of owning entity(player DTO).

                                2.Load the existing assosciated entity from the database.

                                3.Relate each owning entity with the assosciated entity.

                                4.Use save() to save owning entity.

POI(Problem Of Inheritence):

POI is mapping Is-A relationship to database.

To provide the solution for POI,

                                Hibernate has provided three strategies:

  • Table per class
  • Single Table
  • Joined

1.Table per class Strategy:

In this strategy the number of tables will be equal to the number of DTO’s.

Each DTO is mapped to its own table.

Dis-advantage:

  1. Since the number of tables are equal to the number of DTO’s. ‘n’ number of tables will be equal to ‘n’ number of classes
  2. The columns in the super class are repeated in every sub-class table.

2. Single table strategy:

                                In this strategy hibernate will create only one table.

All the DTO’s are mapped to single table.

Dis-advantage:

1.The table contains lot of null values. Hence “NOT NULL” constraint cannot be added to columns.

3. Joined Strategy:

In this strategy the number of tables are equal to the number of DTO’S but the columns are not repeated. The tables are “normalized”.

Dis-advantage of load():

The multiple object cannot be loaded from the database. Hence HQL was used. But HQL uses keywords of SQL and hence not completely object oriented.

There are five core API’s in Hibernate:

                1.criteria(Select *)

                2.criterion(where)

                3.restrictions(conditions)

                4.projections(group)

                5.order(asc/desc order)

1. Criteria

It is an API which is used to load the objects from the Database based on some conditions.                         

To use criteria we have to follow two steps:

1)   Create the criteria.

2)   Process the result.

To create the criteria, we have to use createCriteria(), present in Session object.

The return type of createCriteria() is a Criteria object.

2. Criterion

Criterion is same as where clause in SQL. To relate criteria with criterion we use a add(), present in criteria object. When multiple criterion’s are used then AND is default operation.

3. Restrictions:

It is an API which is used to add the conditions to criteria. It is a class which has some static methods like eq, gt, ge and so on.

Restrictions.xxx() returns an object of Criterion .

4. Projections

It is an API which is used to execute Group functions like avg, max, min, count etc. To execute Group Functions Hibernate has provided a class called as projections, which has some static methods like max, min, rowCount etc.               

To use Projection we have to follow three steps:

1: Create Criteria.

2: Use Projections.xxx methods to obtain a Projection object.

3:To relate criteria with Projection we use a method called as setProjection().

5. Order

It is an API which is used to sort the data in ascending/descending order.                             

To use Order we have to follow three steps:

1: Create Criteria.

2: Use Order.asc or Order.dsc methods to obtain an object of Order.

3: To relate criteria with Order we use a method called as addOrder().

Pagination using Criteria

To paginate the result Hibernate has provided an API called as Criteria.   

To paginate the results we have to use two methods:

  1. setFirstResult (int a1)
  2.  setMaxResults (int a1)

1. setFirstResult (int a1):

This method accepts an integer which specifies the index from where the data should be fetched.

2. setMaxResults (int a1):

This method accepts an integer which specifies the count of number of records that should be fetched.                               

States of hibernate Entity

There are 3 states

                                a)Transient

                                b)Persistent

                                c)Detached

a) Transient

In this state, entity will not have a primary key and it is not associated with the session. To move from transient state to persistent state, we use save()                            

b) Persistent

In this state, entity will have a primary key and it is associated with the session. To move from  persistent state to detached state, we use close()

c) Detached

In this state, entity will have a primary key and it is not associated with the session

Cache

cache
cache

Hibernate caching improves the performance of the application by pooling the object in the cache.        

Hibernate has 2 levels of cache

a) First Level cache

b) Second Level Cache   

a) First Level cache

It is held by Session object. It is not shared between the sessions. By default first level cache is enabled.

The first level cache data will not be available to entire application. An application can use many session object.

b) Second Level Cache

It is held by SessionFactory Object. It is shared between the sessions. By default second level cache is disabled. The second level cache data will be available to entire application. To enable Second Level Cache, we have to use an external provider called as EHCacheProvider.

HTTP methods

GET-Read Record

POST-Insert Record

PUT-Update Record

DELETE-Delete Record

Interview Questions

  1. What is hibernate
  2.  What are the components of hibernate
  3.  Write hibernate configuration file to connect to MySQL and oracle
  4.  What is HQL and explain difference between HQL and SQL
  5.  What is transaction and when it is used                 
  6.   Difference between SessionFactory and Session
  7.   Difference between save,update & saveOrUpdate
  8.   What is POR and explain the strategies?
  9.   What is POI and explain its strategies?
  10.   Explain states of hibernate entity
  11.   Explain cache in hibernate          
  12.   Difference between load and get            

Hibernate resume points(Hibernate 5.x)

  • Knowledge on ORM and its problems
  • Knowledge on components of hibernate
  • Good in HQL and criteria
  • Knowledge on states of hibernate entities
  • Knowledge on cache

Checkout my other posts