Hibernate -  Freddy Gandhi
Object Relational Mapping (ORM)  <ul><li>The term  object/relational mapping (ORM) refers to the technique of mapping a da...
Paradigm Mismatch <ul><li>Problem of Identity </li></ul><ul><li>Problem of  Sub Types </li></ul><ul><li>Problems relating ...
Hibernate Features <ul><li>Hibernate is an object/relational mapping tool for Java environments. </li></ul><ul><li>Elimina...
Benefits of using Hibernate <ul><li>Reduction of development time and effort  otherwise spent with manual data handling in...
Hibernate Usage <ul><li>Hibernate works well in a managed environment with all major J2EE application servers, or even in ...
Hibernate Setup
Installation <ul><li>Download the latest version of Hibernate(e.g. hibernate-3.0.5.zip) from the site  http://www.hibernat...
Configuration Files <ul><li>Hibernate uses 3 configuration files  during runtime, these files need to be present in its Cl...
hibernate.cfg.xml <ul><li>Example  </li></ul><ul><li><hibernate-configuration> </li></ul><ul><li><session-factory> </li></...
hibernate.cfg.xml <ul><li>Hibernate  XML-based configuration.to know the  the JDBC connection parameter(the other approach...
hibernate.properties <ul><li>Please find the attached template of the property file </li></ul>
Application .hbm.xml <ul><li>Example </li></ul><ul><ul><li><hibernate-mapping> </li></ul></ul><ul><ul><li><class name=&quo...
Exercise 1 & Exercise 2
Working with Hibernate
Core Interfaces <ul><li>Configuration Interface : The application uses the configuration instance to specify the location ...
Core Interfaces <ul><li>Transaction Interface :  Optional interface to manage transactions.Hibernate applications may choo...
States of an Instance <ul><li>Instances(of  Persistent Classes ) may exist in one of three states: </li></ul><ul><ul><li>T...
States of an Instance <ul><li>Example: </li></ul><ul><ul><li>Session session = HibernateUtil.currentSession(); </li></ul><...
Basic O/R Mapping
Basic O/R Mapping  <ul><li>Object/relational mappings are defined in an XML document. </li></ul><ul><li>The mapping langua...
Element <hibernate-mapping> <ul><li>The root element in O/R mapping file.Contains the following attributes   </li></ul><ul...
Element <class> <ul><li>You may declare a persistent class using the class element : </li></ul><ul><ul><ul><li>name (optio...
Element <id> <ul><li>Mapped classes  must  declare the primary key column of the database tab: </li></ul><ul><ul><ul><li>n...
Element <property> <ul><li>Mapped classes  must  declare the primary key column of the database tab : </li></ul><ul><ul><u...
Collections & Associations
Collection <ul><li>Hibernate supports all kinds of collection mappings, a <set> being most common. </li></ul><ul><li>The o...
Collection Mapping <ul><li>Example : </li></ul><ul><li><class name=&quot;Department&quot; table=&quot;DEPARTMENT&quot;> </...
Associations <ul><li>Associations refer to relationships between entities </li></ul><ul><li>Using Hibernate, we can repres...
Exercise 3
HQL(Hibernate Query Language)
HQL(Hibernate Query Language) <ul><li>Hibernate is equipped with an extremely powerful query language that (quite intentio...
HQL example 1 <ul><li>E.g. Get a list of all the employees (Table : MASTER_EMPLOYEE) </li></ul><ul><li>SQL :- </li></ul><u...
HQL example 2 <ul><li>E.g. Get a list of all the employees (Table : MASTER_EMPLOYEE) where D_CODE = ’00A’ </li></ul><ul><l...
HQL example 3 <ul><li>E.g. Get a count of all the employees </li></ul><ul><li>SQL :- </li></ul><ul><li>select  count(*) fr...
HQL <ul><li>HQL provides  several other features for data retrieval which include  :- </li></ul><ul><ul><li>Sub querying <...
Appendix <ul><li>ThreadLocal  : </li></ul><ul><li>Each thread that accesses one (via its get or set method) has its own, i...
Appendix <ul><li>Transparent Persistence </li></ul><ul><li>In object-relational mapping products, the ability to directly ...
References <ul><li>URL </li></ul><ul><ul><li>www.hibernate.org </li></ul></ul><ul><li>Reference Material </li></ul><ul><ul...
Upcoming SlideShare
Loading in …5
×

Patni Hibernate

2,113 views

Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Patni Hibernate

  1. 1. Hibernate - Freddy Gandhi
  2. 2. Object Relational Mapping (ORM) <ul><li>The term object/relational mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model. </li></ul><ul><li>Various ORM products include :- </li></ul><ul><ul><li>Apache DB Project </li></ul></ul><ul><ul><li>NET Data Objects </li></ul></ul><ul><ul><li>SimpleORM </li></ul></ul><ul><ul><li>Sybase, Inc. </li></ul></ul><ul><ul><li>Hibernate </li></ul></ul><ul><li>Obtain the complete list of products from :- </li></ul><ul><li>http://www.service-architecture.com/products/object- </li></ul><ul><li>relational_mapping.html </li></ul>
  3. 3. Paradigm Mismatch <ul><li>Problem of Identity </li></ul><ul><li>Problem of Sub Types </li></ul><ul><li>Problems relating to associations </li></ul><ul><li>Problem of object graph navigation </li></ul><ul><li>Result :- </li></ul><ul><li>Significant waste of time and effort </li></ul><ul><li>Solution:- </li></ul><ul><li>Usage of ORM tool </li></ul>
  4. 4. Hibernate Features <ul><li>Hibernate is an object/relational mapping tool for Java environments. </li></ul><ul><li>Eliminates manual data handling involved in SQL and JDBC. </li></ul><ul><li>Direct mapping of an object oriented solution </li></ul><ul><li>Provides Transparent Persistence </li></ul><ul><li>Data query and retrieval facilities with provisions to execute native SQL(s) </li></ul>
  5. 5. Benefits of using Hibernate <ul><li>Reduction of development time and effort otherwise spent with manual data handling in SQL and JDBC. </li></ul><ul><li>Relieve the developer from 95 percent of common data persistence related programming tasks. </li></ul><ul><li>Object oriented solutions can be directly mapped to real world problems.No longer the mapping between the Object orient data model and relational data model is required. </li></ul><ul><li>ORM mapping facilitated using an XML </li></ul><ul><li>Higher Performance depending on usage </li></ul><ul><li>Open Source Project </li></ul>
  6. 6. Hibernate Usage <ul><li>Hibernate works well in a managed environment with all major J2EE application servers, or even in standalone Java applications . </li></ul><ul><li>It is most useful with object-oriented Domain Model and business logic in the Java-based middle-tier. </li></ul><ul><li>Hibernate may not be the best solution for data-centric applications that only use stored-procedures to implement the business logic in the database. </li></ul><ul><li>Hibernate is most suitable for applications based on a rich Domain Model involving complex interaction between entities </li></ul>
  7. 7. Hibernate Setup
  8. 8. Installation <ul><li>Download the latest version of Hibernate(e.g. hibernate-3.0.5.zip) from the site http://www.hibernate.org </li></ul><ul><li>The zip file will contain the Hibernate jar (along with other third party jar files for various features like logging,connection pooling), template of configuration files and source code of example applications implemented using Hibernate </li></ul><ul><li>Set the class path to include the necessary jar files and the configuration files </li></ul>
  9. 9. Configuration Files <ul><li>Hibernate uses 3 configuration files during runtime, these files need to be present in its Class path :- </li></ul><ul><ul><li>hibernate.cfg.xml : Configuration of properties (both related and not related to Hibernate).Contains the ORM Mapping file names </li></ul></ul><ul><ul><li>hibernate.properties : Configuration of properties (both related and not related to Hibernate). </li></ul></ul><ul><ul><li>Application.hbm.xml :This is the ORM mapping file corresponding to your application.The name of this file is defined by the developer (mapping is done in the hibernate.cfg.xml ), e.g. Event.hbm.xml.There can be more than one file like this for the same application </li></ul></ul>
  10. 10. hibernate.cfg.xml <ul><li>Example </li></ul><ul><li><hibernate-configuration> </li></ul><ul><li><session-factory> </li></ul><ul><li><property name= connection.datasource&quot;>java:comp/env/jdbc/quickstart </li></ul><ul><li></property> </li></ul><ul><li><property name=&quot;show_sql&quot;>false</property> </li></ul><ul><li><property name=&quot;dialect&quot;>org.hibernate.dialect.PostgreSQLDialect </li></ul><ul><li></property> </li></ul><ul><li><!-- Mapping files --> </li></ul><ul><li><mapping resource=&quot;Cat.hbm.xml&quot;/> </li></ul><ul><li></session-factory> </li></ul><ul><li></hibernate-configuration> </li></ul>
  11. 11. hibernate.cfg.xml <ul><li>Hibernate XML-based configuration.to know the the JDBC connection parameter(the other approach being the properties file) </li></ul><ul><li>A SessionFactory is Hibernate's concept of a single datastore, multiple databases can be used by creating multiple XML configuration files and creating multiple Configuration and SessionFactory objects in your application. </li></ul><ul><li>The element (resource mapping ) provides the name of the ORM mapping file(s) for the persistent classes of the application </li></ul>
  12. 12. hibernate.properties <ul><li>Please find the attached template of the property file </li></ul>
  13. 13. Application .hbm.xml <ul><li>Example </li></ul><ul><ul><li><hibernate-mapping> </li></ul></ul><ul><ul><li><class name=&quot;Event&quot; table=&quot;EVENTS&quot;> </li></ul></ul><ul><ul><li><id name=&quot;id&quot; column=&quot;EVENT_ID&quot;> </li></ul></ul><ul><ul><li></id> </li></ul></ul><ul><ul><li><property name=&quot;date“ </li></ul></ul><ul><ul><li>type=&quot;timestamp&quot;column=&quot;EVENT_DATE&quot;/> </li></ul></ul><ul><ul><li><property name=&quot;title&quot;/> </li></ul></ul><ul><ul><li></class> </li></ul></ul><ul><ul><li><class name=“Person&quot; table=“PERSON&quot;> </li></ul></ul><ul><ul><li>… . </li></ul></ul><ul><ul><li></class> </li></ul></ul><ul><ul><li></hibernate-mapping> </li></ul></ul>
  14. 14. Exercise 1 & Exercise 2
  15. 15. Working with Hibernate
  16. 16. Core Interfaces <ul><li>Configuration Interface : The application uses the configuration instance to specify the location of the mapping documents and Hibernate-specific properties and then create the SessionFactory </li></ul><ul><li>SessionFactory Interface: A SessionFactory is an expensive-to-create,thread safe object intended to be shared by all application threads.It is created once, usually on application startup, from a Configuration instance . </li></ul><ul><li>Session Interface: A single-threaded, short-lived object representing a conversation between the application and the persistent store. </li></ul>
  17. 17. Core Interfaces <ul><li>Transaction Interface : Optional interface to manage transactions.Hibernate applications may choose not to use this interface, instead manage transactions through their infrastructure code. </li></ul><ul><li>Query Interface : This allows the developer to perform queries against the database and control how the query is executed </li></ul>
  18. 18. States of an Instance <ul><li>Instances(of Persistent Classes ) may exist in one of three states: </li></ul><ul><ul><li>T ransient :The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value). </li></ul></ul><ul><ul><li>Persistent :The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and, perhaps, a corresponding row in the database. For a particular persistence context </li></ul></ul><ul><ul><li>Detached :The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and, perhaps, a corresponding row in the database.For detached instances, Hibernate makes no guarantees about the relationship between persistent identity and Java identity. </li></ul></ul>
  19. 19. States of an Instance <ul><li>Example: </li></ul><ul><ul><li>Session session = HibernateUtil.currentSession(); </li></ul></ul><ul><ul><li>Transaction tx = session.beginTransaction(); </li></ul></ul><ul><ul><li>Person aPerson = (Person) session.load(Person.class, personId); </li></ul></ul><ul><ul><li>Event anEvent = (Event) session.load(Event.class, eventId); </li></ul></ul><ul><ul><li>tx.commit(); </li></ul></ul><ul><ul><li>HibernateUtil.closeSession(); </li></ul></ul><ul><ul><li>aPerson.getEvents().add(anEvent); // aPerson is detached </li></ul></ul><ul><ul><li>Session session2 = HibernateUtil.currentSession(); </li></ul></ul><ul><ul><li>Transaction tx2 = session.beginTransaction(); </li></ul></ul><ul><ul><li>session2.update(aPerson); // Reattachment of aPerson </li></ul></ul><ul><ul><li>tx2.commit(); </li></ul></ul><ul><ul><li>HibernateUtil.closeSession(); </li></ul></ul>
  20. 20. Basic O/R Mapping
  21. 21. Basic O/R Mapping <ul><li>Object/relational mappings are defined in an XML document. </li></ul><ul><li>The mapping language is Java-centric, meaning that mappings are constructed around persistent class declarations, not table declarations. </li></ul><ul><li>A number of tools exist to generate the mapping document, including XDoclet, Middlegen and AndroMDA. </li></ul>
  22. 22. Element <hibernate-mapping> <ul><li>The root element in O/R mapping file.Contains the following attributes </li></ul><ul><ul><ul><li>schema (optional): The name of a database schema. </li></ul></ul></ul><ul><ul><ul><li>catalog (optional): The name of a database catalog. </li></ul></ul></ul><ul><ul><ul><li>default-cascade (optional - defaults to none ): A default cascade style. </li></ul></ul></ul><ul><ul><ul><li>package (optional): Specifies a package prefix to assume for unqualified class names in the mapping document. </li></ul></ul></ul><ul><li>Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping) </li></ul>
  23. 23. Element <class> <ul><li>You may declare a persistent class using the class element : </li></ul><ul><ul><ul><li>name (optional): The fully qualified Java class name of the persistent class (or interface). If this attribute is missing, it is assumed that the mapping is for a non-POJO entity. </li></ul></ul></ul><ul><ul><ul><li>table (optional - defaults to the unqualified class name): The name of its database table. </li></ul></ul></ul><ul><ul><ul><li>mutable (optional, defaults to true): Specifies that instances of the class are (not) mutable. </li></ul></ul></ul><ul><li>Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping) </li></ul>
  24. 24. Element <id> <ul><li>Mapped classes must declare the primary key column of the database tab: </li></ul><ul><ul><ul><li>name (optional): The name of the identifier property. </li></ul></ul></ul><ul><ul><ul><li>type (optional): A name that indicates the Hibernate type. </li></ul></ul></ul><ul><ul><ul><li>column (optional - defaults to the property name): The name of the primary key column. </li></ul></ul></ul><ul><li>There is an alternative <composite-id> declaration to allow access to legacy data with composite keys </li></ul><ul><li>Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping) </li></ul>
  25. 25. Element <property> <ul><li>Mapped classes must declare the primary key column of the database tab : </li></ul><ul><ul><ul><li>name : the name of the property, with an initial lowercase letter. </li></ul></ul></ul><ul><ul><ul><li>column (optional - defaults to the property name): the name of the mapped database table column. This may also be specified by nested <column> element(s). </li></ul></ul></ul><ul><ul><ul><li>type (optional): a name that indicates the Hibernate type. </li></ul></ul></ul><ul><li>Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping) </li></ul>
  26. 26. Collections & Associations
  27. 27. Collection <ul><li>Hibernate supports all kinds of collection mappings, a <set> being most common. </li></ul><ul><li>The other collection mapping include <list>, <map>, <bag> and <array> </li></ul><ul><li>Collection instances are distinguished in the database by the foreign key of the entity that owns the collection.For a many-to-many association(or n:m entity relationship), an association table is needed. This foreign key is referred to as the collection key column (or columns) of the collection table. The collection key column is mapped by the <key> element. </li></ul>
  28. 28. Collection Mapping <ul><li>Example : </li></ul><ul><li><class name=&quot;Department&quot; table=&quot;DEPARTMENT&quot;> </li></ul><ul><li><id name=&quot;id&quot; column=&quot;DEPCODE&quot;> </li></ul><ul><li><generator class=&quot;increment&quot;/> </li></ul><ul><li></id> </li></ul><ul><li><property name=&quot;DeptName&quot; column=&quot;DNAME&quot;/> </li></ul><ul><li><set name=&quot;EMPLIST&quot;> </li></ul><ul><li><key column=&quot;DEPCODE&quot;/> </li></ul><ul><li><one-to-many column = &quot;DEPTID&quot; class=&quot;Employee&quot;/> </li></ul><ul><li></set> </li></ul><ul><li></class> </li></ul>
  29. 29. Associations <ul><li>Associations refer to relationships between entities </li></ul><ul><li>Using Hibernate, we can represent relationships of all cardinality,i.e. one-to-one, one-to-many,many-to-one and many-to-many </li></ul><ul><li>A many-to-many association will result in a link or association table </li></ul><ul><li>Hibernate supports polymorphic association </li></ul>
  30. 30. Exercise 3
  31. 31. HQL(Hibernate Query Language)
  32. 32. HQL(Hibernate Query Language) <ul><li>Hibernate is equipped with an extremely powerful query language that (quite intentionally) looks very much like SQL </li></ul><ul><li>HQL is fully object-oriented, understanding notions like inheritance,polymorphism and association. </li></ul><ul><li>Queries are case-insensitive, except for names of Java classes and properties. </li></ul><ul><li>HQL isn’t a data-manipulation language like SQL.It is used only for object retrieval and not for updating,inserting or deleting data.Object state synchronization is the work of the persistence manager. </li></ul>
  33. 33. HQL example 1 <ul><li>E.g. Get a list of all the employees (Table : MASTER_EMPLOYEE) </li></ul><ul><li>SQL :- </li></ul><ul><li>select * from MASTER_EMPLOYEE EMP </li></ul><ul><li>HQL :- </li></ul><ul><li>from MASTER_EMPLOYEE EMP </li></ul><ul><li>Programmatically :- </li></ul><ul><li>Query q = session.createQuery(“from MASTER_EMPLOYEE EMP ”) ; </li></ul><ul><li>List result = q.list(); </li></ul>
  34. 34. HQL example 2 <ul><li>E.g. Get a list of all the employees (Table : MASTER_EMPLOYEE) where D_CODE = ’00A’ </li></ul><ul><li>SQL :- </li></ul><ul><li>select * from MASTER_EMPLOYEE EMP </li></ul><ul><li>where EMP.D_CODE = ’00A’ </li></ul><ul><li>HQL Programmatically :- </li></ul><ul><li>Query q = session.createQuery(“from MASTER_EMPLOYEE EMP where EMP.D_CODE = :code ”) ; </li></ul><ul><li>q.setString(“code”,”00A”); </li></ul><ul><li>List result = q.list(); </li></ul>
  35. 35. HQL example 3 <ul><li>E.g. Get a count of all the employees </li></ul><ul><li>SQL :- </li></ul><ul><li>select count(*) from MASTER_EMPLOYEE EMP </li></ul><ul><li>HQL Programmatically :- </li></ul><ul><li>Query q = session.createQuery(“select count(*) from MASTER_EMPLOYEE EMP”) ; </li></ul><ul><li>List result = q.list(); </li></ul><ul><li>The List(result) returned in the above case will contain single object of the Integer Class.Incase of functions like avg() the object will be of Float Class </li></ul><ul><li>The supported aggregate functions are </li></ul><ul><ul><li>avg(...), sum(...), min(...), max(...) </li></ul></ul><ul><ul><li>count(*) </li></ul></ul><ul><ul><li>count(...), count(distinct ...), count(all...) </li></ul></ul>
  36. 36. HQL <ul><li>HQL provides several other features for data retrieval which include :- </li></ul><ul><ul><li>Sub querying </li></ul></ul><ul><ul><li>Join types supported by ANSI SQL (e.g. inner join,left outer,etc) </li></ul></ul><ul><ul><li>Polymorphic queries </li></ul></ul><ul><ul><li>Ordering/groping </li></ul></ul><ul><ul><li>Usage of Expressions [e.g. emp.name in ( ‘Rakesh', ‘Manish', ‘Dhiraj' )] </li></ul></ul><ul><ul><li>Executing native SQL queries </li></ul></ul><ul><ul><li>Using stored procedures for querying </li></ul></ul><ul><li>Refer to hibernate_reference.pdf(Chapters : HQL,Criteria Query,Native SQL) </li></ul>
  37. 37. Appendix <ul><li>ThreadLocal : </li></ul><ul><li>Each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal objects are typically private static variables in classes that wish to associate state with a thread (Transaction ID). </li></ul><ul><li>Domain Model : </li></ul><ul><li>An object model of the domain problem that incorporates both behavior and data </li></ul><ul><li>[ BACK ] </li></ul>
  38. 38. Appendix <ul><li>Transparent Persistence </li></ul><ul><li>In object-relational mapping products, the ability to directly manipulate data stored in a relational database using an object programming language is called transparent persistence </li></ul><ul><li>[ BACK ] </li></ul><ul><li>Persistent classes </li></ul><ul><li>Classes in an application that implement the entities of the business problem (e.g. Customer and Order in an E-commerce application) </li></ul><ul><li>[ BACK ] </li></ul>
  39. 39. References <ul><li>URL </li></ul><ul><ul><li>www.hibernate.org </li></ul></ul><ul><li>Reference Material </li></ul><ul><ul><li>hibernate_reference.pdf(can be downloaded from the above site) </li></ul></ul><ul><ul><li>Hibernate in Action(Christian Bauer & Gavin King) </li></ul></ul><ul><li>[ Incase of any doubts or queries about this presentation mail me at freddy.gandhi@patni.com ] </li></ul>

×