Introduction to Hibernate framework

Hibernate was started in 2001 by Gavin King as an alternative to using EJB2-style entity beans. Its mission back then was to simply offer better persistence capabilities than offered by EJB2 by simplifying the complexities and allowing for missing features. Early in 2003, the Hibernate development team began Hibernate2 releases which offered many significant improvements over the first release. JBoss, Inc. (now part of Red Hat) later hired the lead Hibernate developers and worked with them in supporting Hibernate. Hibernate is part of JBoss (a division of Red Hat) Enterprise Middleware System (JEMS) suite of products. [sc name=”Hibernate_Tutorials”]

1. Introduction

Hibernate is an Object-relational mapping (ORM) tool. Object-relational mapping or ORM is a programming method for mapping the objects to the relational model where entities/classes are mapped to tables, instances are mapped to rows and attributes of instances are mapped to columns of table. A “virtual object database” is created that can be used from within the programming language. Hibernate is a persistence framework which is used to persist data from Java environment to database. Persistence is a process of storing the data to some permanent medium and retrieving it back at any point of time even after the application that had created the data ended.

2. Hibernate Architecture

hibernate-architecture-mini The above diagram shows minimal architecture of Hibernate. It creates a layer between Database and the Application. It loads the configuration details like Database connection string, entity classes, mappings etc. Hibernate creates persistent objects which synchronize data between application and database. hibernate-architecture-compre The above diagram shows a comprehensive architecture of Hibernate. In order to persist data to a database, Hibernate create an instance of entity class (Java class mapped with database table). This object is called Transient object as they are not yet associated with the session or not yet persisted to a database. To persist the object to database, the instance of SessionFactory interface is created. SessionFactory is a singleton instance which implements Factory design pattern. SessionFactory loads hibernate.cfg.xml file (Hibernate configuration file. More details in following section) and with the help of TransactionFactory and ConnectionProvider implements all the configuration settings on a database. Each database connection in Hibernate is created by creating an instance of Session interface. Session represents a single connection with database. Session objects are created from SessionFactory object. Hibernate also provides built-in Transaction APIs which abstracts away the application from underlying JDBC or JTA transaction. Each transaction represents a single atomic unit of work. One Session can span through multiple transactions.

2.1 SessionFactory (org.hibernate.SessionFactory)

A thread-safe, immutable cache of compiled mappings for a single database. A factory for org.hibernate.Session instances. A client of org.hibernate.connection.ConnectionProvider. Optionally maintains a second level cache of data that is reusable between transactions at a process or cluster level.

2.2 Session (org.hibernate.Session)

A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC java.sql.Connection. Factory for org.hibernate.Transaction. Maintains a first level cache of persistent the application’s persistent objects and collections; this cache is used when navigating the object graph or looking up objects by identifier.

2.3 Persistent objects and collections

Short-lived, single threaded objects containing persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one org.hibernate.Session. Once the org.hibernate.Session is closed, they will be detached and free to use in any application layer (for example, directly as data transfer objects to and from presentation).

2.4 Transient and detached objects and collections

Instances of persistent classes that are not currently associated with a org.hibernate.Session. They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed org.hibernate.Session.

2.5 Transaction (org.hibernate.Transaction)

(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction. A org.hibernate.Session might span several org.hibernate.Transactions in some cases. However, transaction demarcation, either using the underlying API or org.hibernate.Transaction, is never optional.

2.6 ConnectionProvider (org.hibernate.connection.ConnectionProvider)

(Optional) A factory for, and pool of, JDBC connections. It abstracts the application from underlying javax.sql.DataSource or java.sql.DriverManager. It is not exposed to application, but it can be extended and/or implemented by the developer.

2.7 TransactionFactory (org.hibernate.TransactionFactory)

(Optional) A factory for org.hibernate.Transaction instances. It is not exposed to the application, but it can be extended and/or implemented by the developer.

3. Hibernate Configuration

Hibernate configuration is managed by an instance of org.hibernate.cfg.Configuration. An instance of org.hibernate.cfg.Configuration represents 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 or from Java 5 Annotations. Hibernate provides following types of configurations
  1. hibernate.cfg.xml – A standard XML file which contains hibernate configuration and which resides in root of application’s CLASSPATH
  2. hibernate.properties – A Java compliant property file which holds key value pair for different hibernate configuration strings.
  3. Programmatic configuration – This is the manual approach. The configuration can be defined in Java class.

3.1 hibernate.cfg.xml

This is an alternate way of configuring hibernate. The hibernate.cfg.xml file is a standard XML file which contains all the configuration parameters like database connection, class mappings etc. This file needs to be placed root of CLASSPATH of application. Below is the sample hibernate.cfg.xml file:
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <!-- a SessionFactory instance listed as /jndi/name --> <session-factory name="java:hibernate/SessionFactory"> <!-- properties --> <property name="connection.datasource">java:/comp/env/jdbc/MyEmployeeDB</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">false</property> <property name="transaction.factory_class"> org.hibernate.transaction.JTATransactionFactory </property> <property name="jta.UserTransaction">java:comp/UserTransaction</property> <!-- mapping files --> <mapping resource="net/viralpatel/hibernate/Employee.hbm.xml"/> <mapping resource="net/viralpatel/hibernate/Department.hbm.xml"/> <!-- cache settings --> <class-cache class="net.viralpatel.hibernate.Employee" usage="read-write"/> <class-cache class="net.viralpatel.hibernate.Department" usage="read-only"/> <collection-cache collection="net.viralpatel.hibernate.Department.employees" usage="read-write"/> </session-factory> </hibernate-configuration>
Code language: HTML, XML (xml)
Once the hibernate.cfg.xml file is created and placed in root of application’s CLASSPATH, the same can be loaded in Hibernate using following API.
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Code language: Java (java)
This above code will load default hibernate.cfg.xml file and all the configuration mentioned in it. In case you want to override default naming convention and want to have your own configuration file like “employeedb.cfg.xml”, following API can be used:
SessionFactory sf = new Configuration() .configure("employeedb.cfg.xml") .buildSessionFactory();
Code language: Java (java)

Note: Both hibernate.cfg.xml and hibernate.properties files can be provided simultaneously in an application. In this case hibernate.cfg.xml gets precedence over hibernate.properties.

3.2 hibernate.properties

This is the easiest way to get started with Hibernate. Create a file hibernate.properties and place it in root of your applications CLASSPATH. Below is the sample hibernate.properties file:
hibernate.connection.driver_class=com.mysql.jdbc.Driver hibernate.connection.url= jdbc:mysql://localhost:3306/employee hibernate.connection.username=root hibernate.connection.password=swordfish hibernate.connection.pool_size=1 hibernate.transaction.factory_class = \ org.hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookup_class = \ org.hibernate.transaction.JBossTransactionManagerLookup hibernate.dialect = org.hibernate.dialect.MySQLDialect
Code language: Java (java)
For detail description of Configuration parameters, refer this article Hibernate configuration properties.

3.3 Programmatic configuration

We can obtain a org.hibernate.cfg.Configuration instance by instantiating it directly and specifying XML mapping documents. If the mapping files are in the classpath, use addResource(). For example:
Configuration cfg = new Configuration() .addResource("Employee.hbm.xml") .addResource("Department.hbm.xml");
Code language: Java (java)
An alternative way is to specify the mapped class and allow Hibernate to find the mapping document for you:
Configuration cfg = new Configuration() .addClass(net.viralpatel.hibernate.Employee.class) .addClass(net.viralpatel.hibernate.Department.class);
Code language: Java (java)
Hibernate will then search for mapping files named /net/viralpatel/hibernate/Employee.hbm.xml and /net/viralpatel/hibernate/Department.hbm.xml in the classpath. This approach eliminates any hardcoded filenames. A org.hibernate.cfg.Configuration also allows you to specify configuration properties. For example:
Configuration cfg = new Configuration() .addClass(net.viralpatel.hibernate.Employee.class) .addClass(net.viralpatel.hibernate.Department.class) .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect") .setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test") .setProperty("hibernate.order_updates", "true");
Code language: Java (java)

4. Building a SessionFactory

Once the instance of org.hibernate.cfg.Configuration is created using any of the above method, the singleton instance of SessionFactory can be created as follow:
SessionFactory sessions = cfg.buildSessionFactory();
Code language: Java (java)
Hibernate does allow your application to instantiate more than one org.hibernate.SessionFactory. This is useful if you are using more than one database.

5. Getting Session instance

As noted above, Session represents a communication channel between database and application. Each session represents a factory of transactions. Session can be created from SessionFactory as follows:
Session session = sessions.openSession(); // get a new Session
Code language: Java (java)
Thus, in this article we saw an overview of Hibernate ORM and its architecture. Also we noted its different components like SessionFactory, TransactionFactory, Session etc and APIs to instantiate these objects in your application. In next tutorial, We will write a Hello World Hibernate program using both XML file based configuration and Annotations. Stay tuned! :)
Get our Articles via Email. Enter your email address.

You may also like...

36 Comments

  1. fhatz says:

    very good materials for read for newbie using simple word to explain … keep on the good work… thanks alot!

  2. Bad says:

    Great article! Very helpful! Thanks!

  3. Rayudu says:

    Very good article, and very helpfull.. Thanks a lot

  4. Shaswati Roy says:

    Must say , hibernate architecture in a frame … Thanks a lot!!

  5. Ranjit says:

    very well articulated, must say a nice piece of work!! Truly helpful for me!!
    Thanks a lot dude!! keep up good works!!

  6. Sandy says:

    Excellent tutorials but i have one request please organise tutorials in step by step by manner sometime it is difficult to find out tutorials

  7. dineshkumar says:

    very good article…its very useful for me…..thank u so much

  8. Viral says:

    Can you show me the package structure of hibernate … I am beginner in hibernate and i want to know where to place which file in package …

  9. nikunj says:

    thanx hactic

  10. Luie jose says:

    Great Thanks a lot. please do provide sample code for hibernate using SQL Joins or an example using Hibernate query language.

  11. Jag says:

    awsome tutorial ., keep on putting sample codes of hibernate.

  12. Mithun says:

    Hi Viral

    It is a very nice material. I can suggest you to describe in an detailed manner. Though it is okay.
    But it was some more detailed manner, It would be easy for each and everyone.

    Thanks.

  13. Ramesh says:

    VERY NICE CODING

  14. Arun says:

    attractive and effective notes….

  15. Kalai says:

    very easy to understand

  16. how to manage session in hibernate?

  17. Devilfish87 says:

    Excellent work the article is really well structured understandable even for newbies :)

    Does using org.hibernate.Query (Hibernate query Language ) query.uniqueResult() – affects the JEE application performance and security when comparing with normal methods like findById() ??

    Here is an example :

    Session session = HibernateSessionFactory.getSession();
    		Query query = session.createQuery("from User where Login='" + login + "'");
    		User user = (User) query.uniqueResult(); 

    Thanks

  18. mayur Oza says:

    Excellent article……

  19. Bhabadyuti says:

    Excellent tutorial for newbies..

  20. Anuj says:

    Very good content for the initial learners

  21. Jodu says:

    Excellent tutorial in order to begin a learning of Hibernate. Thanks a lot.
    A french visitor

  22. ram bharath says:

    Can you show me the package structure of hibernate … I am beginner in hibernate and i want to know where to place which file in package …and ur code is too easy to understand,thanks a lot

  23. ram bharath says:

    its too easy to understand

  24. Sreekanth says:

    Its an excellent tutorial for beginners. Could you please let me know the certification to be done for Hibernate.

  25. Ankur says:

    This blog about hibernate is amazing.. you made my week.. what I was searching for
    Good work…
    Thanks a lot
    Ankur

  26. Dheeresh says:

    Very helpful in reminding things…. Thanks Viral

  27. nimavat chetna says:

    This blog about hibernate is amazing.. you made my week.. what I was searching for
    Good work…
    Thanks a lot

  28. Shiva says:

    This article is mirror of official Hibernate Documentation (Tutorial)

  29. subbareddy says:

    Hi,

    This blog is very nice. But I have a doubt in hibernate. If I want to configure 2 or more databases in single cfg file. It is possible or not? If it is possible, How can I get individual database connection? Can you please explain with one example.

  30. Ilavarasan Pandian says:

    Nice one , simple English and good explanation

  31. nimbark paresh says:

    This blog about hibernate is amazing.. you made my week.. what I was searching for Good work…
    Thanks a lot

  32. Addanki Nageshwar says:

    Last past from three days i am facing a issue regarding performance Let me tell you the scenario what is happening and configuration what we did in our project.

    We refering unique key from one table to the another table primary key column and we wrote a HQL query

    select distinct i.ap_invoice_id, i.invoice_number, i.invoice_dt, i.amount, i.created_dt, c.contract_id, c.fms_number, c.project_title, t.task_order_id, t.sys_task_order_no, av.voucher_status, i.received_dt, av.check_no, av.disbursed_dt, av.voucher_amt, i.modified_dt, i.ext_type, i.ext_number from vc.reg_master m join vc.registration r on m.reg_master_id = r.reg_master_id join vc.ecms_vendor v on m.ein = v.tax_id join vc.ecms_ap_invoice i on v.vendor_id = i.vendor_id join vc.ecms_contract c on i.pin = c.pin left join vc.ecms_ap_voucher av on i.ap_voucher_id = av.ap_voucher_id left join vc.ecms_task_order t on i.task_order_id = t.task_order_id where r.user_name = ‘nageshwar12’ and c.mod_no is null and c.disable_flg != ‘Y’ order by i.modified_dt desc

    It is fetching another table data of Contract table

    Internal Select Query is executing when i tried show sql= true

    Hibernate:
    /* load gov.fd.vc.model.EcmsContract */ select
    ecmscontra0_.ecms_contract_id as ecms1_5_0_,
    ecmscontra0_.vendor_id as vendor2_5_0_,
    ecmscontra0_.contract_id as contract3_5_0_,
    ecmscontra0_.contract_action_id as contract4_5_0_,
    ecmscontra0_.vendor_proposed_id as vendor5_5_0_,
    ecmscontra0_.pin as pin5_0_,
    ecmscontra0_.legacy_pin as legacy7_5_0_,
    ecmscontra0_.req_no as req8_5_0_,
    ecmscontra0_.po_no as po9_5_0_,
    ecmscontra0_.fn_no as fn10_5_0_,
    ecmscontra0_.unit_req_no as unit11_5_0_,
    ecmscontra0_.fiscal_year as fiscal12_5_0_,
    ecmscontra0_.stage as stage5_0_,
    ecmscontra0_.priority as priority5_0_,
    ecmscontra0_.contract_status as contract15_5_0_,
    ecmscontra0_.legacy_contract_flg as legacy16_5_0_,
    ecmscontra0_.updated_legacy as updated17_5_0_,
    ecmscontra0_.unit_head_flg as unit18_5_0_,
    ecmscontra0_.unit_director_flg as unit19_5_0_,
    ecmscontra0_.submit_flg as submit20_5_0_,
    ecmscontra0_.order_type as order21_5_0_,
    ecmscontra0_.amount as amount5_0_,
    ecmscontra0_.project_title as project23_5_0_,
    ecmscontra0_.description as descrip24_5_0_,
    ecmscontra0_.duration_month as duration25_5_0_,
    ecmscontra0_.duration_year as duration26_5_0_,
    ecmscontra0_.contract_start_dt as contract27_5_0_,
    ecmscontra0_.contract_end_dt as contract28_5_0_,
    ecmscontra0_.award_amt as award29_5_0_,
    ecmscontra0_.award_dt as award30_5_0_,
    ecmscontra0_.document_type as document31_5_0_,
    ecmscontra0_.payement_paid_amt as payement32_5_0_,
    ecmscontra0_.payement_check_no as payement33_5_0_,
    ecmscontra0_.payement_voucher_no as payement34_5_0_,
    ecmscontra0_.payement_dt as payement35_5_0_,
    ecmscontra0_.prepared_dt as prepared36_5_0_,
    ecmscontra0_.prepared_by as prepared37_5_0_,
    ecmscontra0_.payement_terms as payement38_5_0_,
    ecmscontra0_.title as title5_0_,
    ecmscontra0_.mstr_submitting_unit_id as mstr40_5_0_,
    ecmscontra0_.requested_by as requested41_5_0_,
    ecmscontra0_.responsible_person as respons42_5_0_,
    ecmscontra0_.telephone_number as telephone43_5_0_,
    ecmscontra0_.special_project as special44_5_0_,
    ecmscontra0_.i_number as i45_5_0_,
    ecmscontra0_.items_req_details as items46_5_0_,
    ecmscontra0_.pre_encumbrance_flg as pre47_5_0_,
    ecmscontra0_.encumbrance_flg as encumbr48_5_0_,
    ecmscontra0_.fms_number as fms49_5_0_,
    ecmscontra0_.fms_acceptance_dt as fms50_5_0_,
    ecmscontra0_.self_bid_flg as self51_5_0_,
    ecmscontra0_.incl_warranty_flg as incl52_5_0_,
    ecmscontra0_.warranty as warranty5_0_,
    ecmscontra0_.solicitation_flg as solicit54_5_0_,
    ecmscontra0_.determination_flg as determi55_5_0_,
    ecmscontra0_.award_flg as award56_5_0_,
    ecmscontra0_.reg_flg as reg57_5_0_,
    ecmscontra0_.vendor_tbd_flg as vendor58_5_0_,
    ecmscontra0_.disable_flg as disable59_5_0_,
    ecmscontra0_.created_user as created60_5_0_,
    ecmscontra0_.created_dt as created61_5_0_,
    ecmscontra0_.modified_user as modified62_5_0_,
    ecmscontra0_.modified_dt as modified63_5_0_,
    ecmscontra0_.sys_unit_req_no as sys64_5_0_,
    ecmscontra0_.unit_purchase_sup_flg as unit65_5_0_,
    ecmscontra0_.purchase_agent_flg as purchase66_5_0_,
    ecmscontra0_.expedite_flg as expedite67_5_0_,
    ecmscontra0_.problem_flg as problem68_5_0_,
    ecmscontra0_.mod_no as mod69_5_0_,
    ecmscontra0_.mod_amt_flg as mod70_5_0_,
    ecmscontra0_.mod_term_flg as mod71_5_0_,
    ecmscontra0_.mod_amt as mod72_5_0_,
    ecmscontra0_.mod_term_from as mod73_5_0_,
    ecmscontra0_.mod_term_to as mod74_5_0_,
    ecmscontra0_.mod_line_item_flg as mod75_5_0_,
    ecmscontra0_.mod_bud_source_flg as mod76_5_0_,
    ecmscontra0_.enc_flow_flg as enc77_5_0_,
    ecmscontra0_.mod_detail_desc as mod78_5_0_,
    ecmscontra0_.req_purchase_flg as req79_5_0_,
    ecmscontra0_.evaluation_flg as evaluation80_5_0_,
    ecmscontra0_.vendor_contact_id as vendor81_5_0_,
    ecmscontra0_.mod_scope_flg as mod82_5_0_,
    ecmscontra0_.change_order_flg as change83_5_0_,
    ecmscontra0_.formal_contract_flg as formal84_5_0_,
    ecmscontra0_.task_order_flg as task85_5_0_,
    ecmscontra0_.short_form_flg as short86_5_0_,
    ecmscontra0_.open_amt as open87_5_0_,
    ecmscontra0_.closed_amt as closed88_5_0_,
    ecmscontra0_.fms_modification_number as fms89_5_0_,
    ecmscontra0_.nysid_contract_applicable_flg as nysid90_5_0_,
    ecmscontra0_.nysid_exercised_rights_flg as nysid91_5_0_,
    ecmscontra0_.fms_agency_number as fms92_5_0_,
    ecmscontra0_.ap_flow_flg as ap93_5_0_,
    ecmscontra0_.old_pin as old94_5_0_,
    ecmscontra0_.unit_inspector as unit95_5_0_,
    ecmscontra0_.notes_added_flg as notes96_5_0_,
    ecmscontra0_.contract_revised_dt as contract97_5_0_,
    ecmscontra0_.append_stage as append98_5_0_,
    ecmscontra0_.append_stage_2 as append99_5_0_
    from
    vc.ecms_contract ecmscontra0_
    where
    ecmscontra0_.contract_id=?

    These above query Hibernate is loading automatically here contract_id is a unique key in the table. This object should be load on demand but it is loading early it making application down
    I am attaching Model class diagram so that it may help what infrastructure we are using

    Thanks & Regards
    Addanki Nageshwar
    RedRockItSolutions
    Software Developer
    India

  33. Nikhil says:

    Sir,in which year hibernate framework introduce in India

  34. Bhargav Siitapara says:

    it’s a helpful tutorial for a beginer of hibernate keep it up and upload a more tutorial and live project so we can lean a lot from that.

  35. Karamjit Singh Sehdev says:

    Sir,

    You have mentioned that (an instance of a session interface is created).Since its an interface then how an instance can be created. Kindly check the given link. (http://viralpatel.net/introduction-to-hibernate-framework-architecture/)

  36. shrija says:

    Well, your blog is quite interesting and helpful. I just loved reading your blog.
    Wonderful points you have mentioned here, Thank you for sharing.

Leave a Reply

Your email address will not be published. Required fields are marked *