SlideShare a Scribd company logo
Hibernate -  Freddy Gandhi
Object Relational Mapping (ORM)  The term  object/relational mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model. Various ORM products include :- Apache DB Project  NET Data Objects SimpleORM Sybase, Inc. Hibernate  Obtain the complete list of  products from :- http://www.service-architecture.com/products/object- relational_mapping.html
Paradigm Mismatch Problem of Identity Problem of  Sub Types Problems relating to associations Problem of object graph navigation Result :- Significant waste of time and effort Solution:- Usage of ORM tool
Hibernate Features Hibernate is an object/relational mapping tool for Java environments. Eliminates manual data handling involved in  SQL and JDBC. Direct mapping of an  object oriented solution Provides  Transparent Persistence Data query and retrieval facilities with provisions to execute native SQL(s)
Benefits of using Hibernate Reduction of development time and effort  otherwise spent with manual data handling in SQL and JDBC. Relieve the developer from 95 percent of common data persistence related programming tasks. 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. ORM mapping facilitated using an XML Higher Performance depending on usage Open Source Project
Hibernate Usage Hibernate works well in a managed environment with all major J2EE application servers, or even in standalone Java applications  . It is most useful with object-oriented  Domain Model  and business logic in the Java-based middle-tier. Hibernate may not be the best solution for data-centric applications that only use stored-procedures to implement the business logic in the database. Hibernate is most suitable for applications  based on a rich  Domain Model  involving complex interaction between entities
Hibernate Setup
Installation Download the latest version of Hibernate(e.g. hibernate-3.0.5.zip) from the site  http://www.hibernate.org 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 Set the class path  to include the necessary jar files and the configuration files
Configuration Files Hibernate uses 3 configuration files  during runtime, these files need to be present in its Class path :- hibernate.cfg.xml  : Configuration of properties (both related and not related to Hibernate).Contains the ORM Mapping file names hibernate.properties  : Configuration of properties (both related and not related to Hibernate). 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
hibernate.cfg.xml Example  <hibernate-configuration> <session-factory> <property name=  connection.datasource&quot;>java:comp/env/jdbc/quickstart </property> <property name=&quot;show_sql&quot;>false</property> <property name=&quot;dialect&quot;>org.hibernate.dialect.PostgreSQLDialect </property> <!-- Mapping files --> <mapping resource=&quot;Cat.hbm.xml&quot;/> </session-factory> </hibernate-configuration>
hibernate.cfg.xml Hibernate  XML-based configuration.to know the  the JDBC connection parameter(the other approach being the properties file) 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. The  element (resource mapping ) provides the name of the ORM mapping file(s) for the persistent classes of the application
hibernate.properties Please find the attached template of the property file
Application .hbm.xml Example <hibernate-mapping> <class name=&quot;Event&quot; table=&quot;EVENTS&quot;> <id name=&quot;id&quot; column=&quot;EVENT_ID&quot;> </id> <property name=&quot;dateโ€œ type=&quot;timestamp&quot;column=&quot;EVENT_DATE&quot;/> <property name=&quot;title&quot;/> </class> <class name=โ€œPerson&quot; table=โ€œPERSON&quot;> โ€ฆ . </class> </hibernate-mapping>
Exercise 1 & Exercise 2
Working with Hibernate
Core Interfaces 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 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 . Session Interface:  A single-threaded, short-lived object representing a conversation between the application and the persistent store.
Core Interfaces Transaction Interface :  Optional interface to manage transactions.Hibernate applications may choose not to use this interface, instead  manage transactions through their infrastructure code. Query Interface  :  This allows the developer to perform queries against the database and control how the query is executed
States of an Instance Instances(of  Persistent Classes ) may exist in one of three states: T ransient  :The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value). 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 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.
States of an Instance Example: Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); Person aPerson = (Person) session.load(Person.class, personId); Event anEvent = (Event) session.load(Event.class, eventId); tx.commit(); HibernateUtil.closeSession(); aPerson.getEvents().add(anEvent); // aPerson is detached Session session2 = HibernateUtil.currentSession(); Transaction tx2 = session.beginTransaction(); session2.update(aPerson); // Reattachment of aPerson tx2.commit(); HibernateUtil.closeSession();
Basic O/R Mapping
Basic O/R Mapping  Object/relational mappings are defined in an XML document. The mapping language is Java-centric, meaning that mappings are constructed around persistent class declarations, not table declarations. A number of tools exist to generate the mapping document, including XDoclet, Middlegen and AndroMDA.
Element <hibernate-mapping> The root element in O/R mapping file.Contains the following attributes   schema  (optional): The name of a database schema. catalog  (optional): The name of a database catalog. default-cascade  (optional - defaults to  none ): A default cascade style. package  (optional): Specifies a package prefix to assume for unqualified class names in the mapping document. Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping)
Element <class> You may declare a persistent class using the class element : 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. table (optional - defaults to the unqualified class name): The name of its database table. mutable (optional, defaults to true): Specifies that instances of the class are (not) mutable. Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping)
Element <id> Mapped classes  must  declare the primary key column of the database tab: name  (optional): The name of the identifier property. type  (optional): A name that indicates the Hibernate type. column  (optional - defaults to the property name): The name of the primary key column. There is an alternative  <composite-id>  declaration to allow access to legacy data with composite keys Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping)
Element <property> Mapped classes  must  declare the primary key column of the database tab : name : the name of the property, with an initial lowercase letter. 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). type  (optional): a name that indicates the Hibernate type. Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping)
Collections & Associations
Collection Hibernate supports all kinds of collection mappings, a <set> being most common. The other collection mapping include <list>, <map>, <bag> and <array> 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.
Collection Mapping Example : <class name=&quot;Department&quot; table=&quot;DEPARTMENT&quot;> <id name=&quot;id&quot; column=&quot;DEPCODE&quot;> <generator class=&quot;increment&quot;/> </id> <property name=&quot;DeptName&quot;  column=&quot;DNAME&quot;/> <set name=&quot;EMPLIST&quot;> <key column=&quot;DEPCODE&quot;/> <one-to-many column = &quot;DEPTID&quot; class=&quot;Employee&quot;/> </set> </class>
Associations Associations refer to relationships between entities Using Hibernate, we can represent relationships of all cardinality,i.e. one-to-one, one-to-many,many-to-one and many-to-many A many-to-many association will result  in a link or association table Hibernate supports polymorphic association
Exercise 3
HQL(Hibernate Query Language)
HQL(Hibernate Query Language) Hibernate is equipped with an extremely powerful query language that (quite intentionally) looks very much like SQL HQL is fully object-oriented, understanding notions like inheritance,polymorphism and association. Queries are case-insensitive, except for names of Java classes and properties. 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.
HQL example 1 E.g. Get a list of all the employees (Table : MASTER_EMPLOYEE) SQL :- select  * from MASTER_EMPLOYEE EMP HQL :- from  MASTER_EMPLOYEE EMP Programmatically :- Query q = session.createQuery(โ€œfrom  MASTER_EMPLOYEE EMP โ€) ; List  result = q.list();
HQL example 2 E.g. Get a list of all the employees (Table : MASTER_EMPLOYEE) where D_CODE = โ€™00Aโ€™ SQL :- select  * from MASTER_EMPLOYEE EMP  where EMP.D_CODE = โ€™00Aโ€™ HQL Programmatically :- Query q = session.createQuery(โ€œfrom  MASTER_EMPLOYEE EMP  where EMP.D_CODE = :code โ€) ; q.setString(โ€œcodeโ€,โ€00Aโ€); List  result = q.list();
HQL example 3 E.g. Get a count of all the employees SQL :- select  count(*) from MASTER_EMPLOYEE EMP  HQL Programmatically :- Query q = session.createQuery(โ€œselect count(*) from  MASTER_EMPLOYEE EMPโ€) ; List  result = q.list(); 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 The supported aggregate functions are avg(...), sum(...), min(...), max(...) count(*) count(...), count(distinct ...), count(all...)
HQL HQL provides  several other features for data retrieval which include  :- Sub querying Join types supported by ANSI SQL (e.g. inner join,left outer,etc) Polymorphic queries Ordering/groping Usage of Expressions [e.g. emp.name in ( โ€˜Rakesh', โ€˜Manish', โ€˜Dhiraj' )] Executing native SQL queries Using stored procedures for querying Refer to hibernate_reference.pdf(Chapters : HQL,Criteria Query,Native SQL)
Appendix ThreadLocal  : 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). Domain Model : An object model of the domain problem that incorporates both behavior and data [ BACK ]
Appendix Transparent Persistence 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 [ BACK ] Persistent classes   Classes in an application that implement the entities of the business problem (e.g. Customer and Order in an E-commerce application) [ BACK ]
References URL www.hibernate.org Reference Material hibernate_reference.pdf(can be downloaded from the above site) Hibernate in Action(Christian Bauer & Gavin King) [ Incase of any doubts or queries about this presentation mail me at freddy.gandhi@patni.com ]
Ad

More Related Content

What's hot (20)

Enterprise Spring
Enterprise SpringEnterprise Spring
Enterprise Spring
Emprovise
ย 
NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)
Samnang Chhun
ย 
StrategiesForUsingMetadata
StrategiesForUsingMetadataStrategiesForUsingMetadata
StrategiesForUsingMetadata
Suite Solutions
ย 
Overview of the DITA Open Toolkit
Overview of the DITA Open ToolkitOverview of the DITA Open Toolkit
Overview of the DITA Open Toolkit
Suite Solutions
ย 
JSP Standard Tag Library
JSP Standard Tag LibraryJSP Standard Tag Library
JSP Standard Tag Library
Ilio Catallo
ย 
Hibernate III
Hibernate IIIHibernate III
Hibernate III
People Strategists
ย 
Hibernate
HibernateHibernate
Hibernate
Harish Patil ( ใƒใƒชใ‚ทใƒฅใƒ‘ใƒ†ใ‚คใƒซ)
ย 
Oracle Sql Developer Data Modeler 3 3 new features
Oracle Sql Developer Data Modeler 3 3 new featuresOracle Sql Developer Data Modeler 3 3 new features
Oracle Sql Developer Data Modeler 3 3 new features
Philip Stoyanov
ย 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
Raji Ghawi
ย 
NHibernate for .NET
NHibernate for .NETNHibernate for .NET
NHibernate for .NET
Guo Albert
ย 
Doctrine 2 - Introduction
Doctrine 2 - IntroductionDoctrine 2 - Introduction
Doctrine 2 - Introduction
Diego Lewin
ย 
NHibernate
NHibernateNHibernate
NHibernate
gabrielcerutti
ย 
An Introduction to the Jena API
An Introduction to the Jena APIAn Introduction to the Jena API
An Introduction to the Jena API
Craig Trim
ย 
NHibernate
NHibernateNHibernate
NHibernate
Andriy Buday
ย 
Introduction to NHibernate
Introduction to NHibernateIntroduction to NHibernate
Introduction to NHibernate
Dublin Alt,Net
ย 
Triplestore and SPARQL
Triplestore and SPARQLTriplestore and SPARQL
Triplestore and SPARQL
Lino Valdivia
ย 
2008.07.17 ๋ฐœํ‘œ
2008.07.17 ๋ฐœํ‘œ2008.07.17 ๋ฐœํ‘œ
2008.07.17 ๋ฐœํ‘œ
Sunjoo Park
ย 
Graph db as metastore
Graph db as metastoreGraph db as metastore
Graph db as metastore
Haris Khan
ย 
Introduction To NHibernate
Introduction To NHibernateIntroduction To NHibernate
Introduction To NHibernate
Emad Alashi
ย 
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
OWSCIS: Ontology and Web Service based Cooperation of Information SourcesOWSCIS: Ontology and Web Service based Cooperation of Information Sources
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
Raji Ghawi
ย 
Enterprise Spring
Enterprise SpringEnterprise Spring
Enterprise Spring
Emprovise
ย 
NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)
Samnang Chhun
ย 
StrategiesForUsingMetadata
StrategiesForUsingMetadataStrategiesForUsingMetadata
StrategiesForUsingMetadata
Suite Solutions
ย 
Overview of the DITA Open Toolkit
Overview of the DITA Open ToolkitOverview of the DITA Open Toolkit
Overview of the DITA Open Toolkit
Suite Solutions
ย 
JSP Standard Tag Library
JSP Standard Tag LibraryJSP Standard Tag Library
JSP Standard Tag Library
Ilio Catallo
ย 
Oracle Sql Developer Data Modeler 3 3 new features
Oracle Sql Developer Data Modeler 3 3 new featuresOracle Sql Developer Data Modeler 3 3 new features
Oracle Sql Developer Data Modeler 3 3 new features
Philip Stoyanov
ย 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
Raji Ghawi
ย 
NHibernate for .NET
NHibernate for .NETNHibernate for .NET
NHibernate for .NET
Guo Albert
ย 
Doctrine 2 - Introduction
Doctrine 2 - IntroductionDoctrine 2 - Introduction
Doctrine 2 - Introduction
Diego Lewin
ย 
An Introduction to the Jena API
An Introduction to the Jena APIAn Introduction to the Jena API
An Introduction to the Jena API
Craig Trim
ย 
NHibernate
NHibernateNHibernate
NHibernate
Andriy Buday
ย 
Introduction to NHibernate
Introduction to NHibernateIntroduction to NHibernate
Introduction to NHibernate
Dublin Alt,Net
ย 
Triplestore and SPARQL
Triplestore and SPARQLTriplestore and SPARQL
Triplestore and SPARQL
Lino Valdivia
ย 
2008.07.17 ๋ฐœํ‘œ
2008.07.17 ๋ฐœํ‘œ2008.07.17 ๋ฐœํ‘œ
2008.07.17 ๋ฐœํ‘œ
Sunjoo Park
ย 
Graph db as metastore
Graph db as metastoreGraph db as metastore
Graph db as metastore
Haris Khan
ย 
Introduction To NHibernate
Introduction To NHibernateIntroduction To NHibernate
Introduction To NHibernate
Emad Alashi
ย 
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
OWSCIS: Ontology and Web Service based Cooperation of Information SourcesOWSCIS: Ontology and Web Service based Cooperation of Information Sources
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
Raji Ghawi
ย 

Viewers also liked (20)

15 jpaql
15 jpaql15 jpaql
15 jpaql
thirumuru2012
ย 
Ejb5
Ejb5Ejb5
Ejb5
patinijava
ย 
JPQL/ JPA Activity 1
JPQL/ JPA Activity 1JPQL/ JPA Activity 1
JPQL/ JPA Activity 1
SFI
ย 
JPQL/ JPA Activity 2
JPQL/ JPA Activity 2JPQL/ JPA Activity 2
JPQL/ JPA Activity 2
SFI
ย 
15 jpa
15 jpa15 jpa
15 jpa
thirumuru2012
ย 
Web Services Part 2
Web Services Part 2Web Services Part 2
Web Services Part 2
patinijava
ย 
Working with jpa
Working with jpaWorking with jpa
Working with jpa
Ondrej Mihรกlyi
ย 
JPQL/ JPA Activity 3
JPQL/ JPA  Activity 3JPQL/ JPA  Activity 3
JPQL/ JPA Activity 3
SFI
ย 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applications
Ondrej Mihรกlyi
ย 
Introduction to developing modern web apps
Introduction to developing modern web appsIntroduction to developing modern web apps
Introduction to developing modern web apps
Fabricio Epaminondas
ย 
Quickstart for continuous integration
Quickstart for continuous integrationQuickstart for continuous integration
Quickstart for continuous integration
Fabricio Epaminondas
ย 
FinelyMe๏ผJustFit Intro
FinelyMe๏ผJustFit IntroFinelyMe๏ผJustFit Intro
FinelyMe๏ผJustFit Intro
Cheng Ta Yeh
ย 
Continuous integration practices to improve the software quality
Continuous integration practices to improve the software qualityContinuous integration practices to improve the software quality
Continuous integration practices to improve the software quality
Fabricio Epaminondas
ย 
Web Services Part 1
Web Services Part 1Web Services Part 1
Web Services Part 1
patinijava
ย 
Designing Scalable Applications
Designing Scalable ApplicationsDesigning Scalable Applications
Designing Scalable Applications
Fabricio Epaminondas
ย 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
patinijava
ย 
Continuous testing in agile projects 2015
Continuous testing in agile projects 2015Continuous testing in agile projects 2015
Continuous testing in agile projects 2015
Fabricio Epaminondas
ย 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
Cheng Ta Yeh
ย 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
Arturs Drozdovs
ย 
Introduction To Spring
Introduction To SpringIntroduction To Spring
Introduction To Spring
Ilio Catallo
ย 
JPQL/ JPA Activity 1
JPQL/ JPA Activity 1JPQL/ JPA Activity 1
JPQL/ JPA Activity 1
SFI
ย 
JPQL/ JPA Activity 2
JPQL/ JPA Activity 2JPQL/ JPA Activity 2
JPQL/ JPA Activity 2
SFI
ย 
Web Services Part 2
Web Services Part 2Web Services Part 2
Web Services Part 2
patinijava
ย 
JPQL/ JPA Activity 3
JPQL/ JPA  Activity 3JPQL/ JPA  Activity 3
JPQL/ JPA Activity 3
SFI
ย 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applications
Ondrej Mihรกlyi
ย 
Introduction to developing modern web apps
Introduction to developing modern web appsIntroduction to developing modern web apps
Introduction to developing modern web apps
Fabricio Epaminondas
ย 
Quickstart for continuous integration
Quickstart for continuous integrationQuickstart for continuous integration
Quickstart for continuous integration
Fabricio Epaminondas
ย 
FinelyMe๏ผJustFit Intro
FinelyMe๏ผJustFit IntroFinelyMe๏ผJustFit Intro
FinelyMe๏ผJustFit Intro
Cheng Ta Yeh
ย 
Continuous integration practices to improve the software quality
Continuous integration practices to improve the software qualityContinuous integration practices to improve the software quality
Continuous integration practices to improve the software quality
Fabricio Epaminondas
ย 
Web Services Part 1
Web Services Part 1Web Services Part 1
Web Services Part 1
patinijava
ย 
Designing Scalable Applications
Designing Scalable ApplicationsDesigning Scalable Applications
Designing Scalable Applications
Fabricio Epaminondas
ย 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
patinijava
ย 
Continuous testing in agile projects 2015
Continuous testing in agile projects 2015Continuous testing in agile projects 2015
Continuous testing in agile projects 2015
Fabricio Epaminondas
ย 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
Cheng Ta Yeh
ย 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
Arturs Drozdovs
ย 
Introduction To Spring
Introduction To SpringIntroduction To Spring
Introduction To Spring
Ilio Catallo
ย 
Ad

Similar to Patni Hibernate (20)

Hibernate
HibernateHibernate
Hibernate
Murali Pachiyappan
ย 
Hibernate.pdf
Hibernate.pdfHibernate.pdf
Hibernate.pdf
SaadAnsari73
ย 
Basic Hibernate Final
Basic Hibernate FinalBasic Hibernate Final
Basic Hibernate Final
Rafael Coutinho
ย 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
Nguyen Cao
ย 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
IMC Institute
ย 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
Aneega
ย 
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Baruch Sadogursky
ย 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
Software Park Thailand
ย 
Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1
Asad Khan
ย 
Using SPMetal for faster SharePoint development
Using SPMetal for faster SharePoint developmentUsing SPMetal for faster SharePoint development
Using SPMetal for faster SharePoint development
Pranav Sharma
ย 
Compass Framework
Compass FrameworkCompass Framework
Compass Framework
Lukas Vlcek
ย 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
Mumbai Academisc
ย 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
Ranjan Kumar
ย 
Introduction to Hibernate
Introduction to HibernateIntroduction to Hibernate
Introduction to Hibernate
Krishnakanth Goud
ย 
Hibernate
HibernateHibernate
Hibernate
Ajay K
ย 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tool
javaease
ย 
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdfSpring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
abdelr7man3mad2004
ย 
TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6
Lokesh Singrol
ย 
Hibernate
HibernateHibernate
Hibernate
Prashant Kalkar
ย 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
dwm042
ย 
Hibernate.pdf
Hibernate.pdfHibernate.pdf
Hibernate.pdf
SaadAnsari73
ย 
Basic Hibernate Final
Basic Hibernate FinalBasic Hibernate Final
Basic Hibernate Final
Rafael Coutinho
ย 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
Nguyen Cao
ย 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
IMC Institute
ย 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
Aneega
ย 
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Baruch Sadogursky
ย 
Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1
Asad Khan
ย 
Using SPMetal for faster SharePoint development
Using SPMetal for faster SharePoint developmentUsing SPMetal for faster SharePoint development
Using SPMetal for faster SharePoint development
Pranav Sharma
ย 
Compass Framework
Compass FrameworkCompass Framework
Compass Framework
Lukas Vlcek
ย 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
Mumbai Academisc
ย 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
Ranjan Kumar
ย 
Introduction to Hibernate
Introduction to HibernateIntroduction to Hibernate
Introduction to Hibernate
Krishnakanth Goud
ย 
Hibernate
HibernateHibernate
Hibernate
Ajay K
ย 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tool
javaease
ย 
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdfSpring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
abdelr7man3mad2004
ย 
TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6
Lokesh Singrol
ย 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
dwm042
ย 
Ad

More from patinijava (14)

Struts N E W
Struts N E WStruts N E W
Struts N E W
patinijava
ย 
Session Management
Session  ManagementSession  Management
Session Management
patinijava
ย 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T S
patinijava
ย 
Struts Java I I Lecture 8
Struts  Java  I I  Lecture 8Struts  Java  I I  Lecture 8
Struts Java I I Lecture 8
patinijava
ย 
Servlet Api
Servlet ApiServlet Api
Servlet Api
patinijava
ย 
Servlet11
Servlet11Servlet11
Servlet11
patinijava
ย 
Sping Slide 6
Sping Slide 6Sping Slide 6
Sping Slide 6
patinijava
ย 
Entity Manager
Entity ManagerEntity Manager
Entity Manager
patinijava
ย 
Ejb6
Ejb6Ejb6
Ejb6
patinijava
ย 
Ejb4
Ejb4Ejb4
Ejb4
patinijava
ย 
Webbasics
WebbasicsWebbasics
Webbasics
patinijava
ย 
Internetbasics
InternetbasicsInternetbasics
Internetbasics
patinijava
ย 
Jsp
JspJsp
Jsp
patinijava
ย 
Portlet
PortletPortlet
Portlet
patinijava
ย 
Struts N E W
Struts N E WStruts N E W
Struts N E W
patinijava
ย 
Session Management
Session  ManagementSession  Management
Session Management
patinijava
ย 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T S
patinijava
ย 
Struts Java I I Lecture 8
Struts  Java  I I  Lecture 8Struts  Java  I I  Lecture 8
Struts Java I I Lecture 8
patinijava
ย 
Servlet Api
Servlet ApiServlet Api
Servlet Api
patinijava
ย 
Servlet11
Servlet11Servlet11
Servlet11
patinijava
ย 
Sping Slide 6
Sping Slide 6Sping Slide 6
Sping Slide 6
patinijava
ย 
Entity Manager
Entity ManagerEntity Manager
Entity Manager
patinijava
ย 
Webbasics
WebbasicsWebbasics
Webbasics
patinijava
ย 
Internetbasics
InternetbasicsInternetbasics
Internetbasics
patinijava
ย 
Portlet
PortletPortlet
Portlet
patinijava
ย 

Recently uploaded (20)

Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
ย 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
ย 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
ย 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
ย 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
ย 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
ย 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
ย 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
ย 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
ย 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
ย 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
ย 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
ย 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
ย 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
ย 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
ย 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
ย 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
ย 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
ย 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
ย 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
ย 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
ย 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
ย 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
ย 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
ย 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
ย 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
ย 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
ย 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
ย 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
ย 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
ย 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
ย 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
ย 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
ย 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
ย 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
ย 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
ย 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
ย 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
ย 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
ย 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
ย 

Patni Hibernate

  • 1. Hibernate - Freddy Gandhi
  • 2. Object Relational Mapping (ORM) The term object/relational mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model. Various ORM products include :- Apache DB Project NET Data Objects SimpleORM Sybase, Inc. Hibernate Obtain the complete list of products from :- http://www.service-architecture.com/products/object- relational_mapping.html
  • 3. Paradigm Mismatch Problem of Identity Problem of Sub Types Problems relating to associations Problem of object graph navigation Result :- Significant waste of time and effort Solution:- Usage of ORM tool
  • 4. Hibernate Features Hibernate is an object/relational mapping tool for Java environments. Eliminates manual data handling involved in SQL and JDBC. Direct mapping of an object oriented solution Provides Transparent Persistence Data query and retrieval facilities with provisions to execute native SQL(s)
  • 5. Benefits of using Hibernate Reduction of development time and effort otherwise spent with manual data handling in SQL and JDBC. Relieve the developer from 95 percent of common data persistence related programming tasks. 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. ORM mapping facilitated using an XML Higher Performance depending on usage Open Source Project
  • 6. Hibernate Usage Hibernate works well in a managed environment with all major J2EE application servers, or even in standalone Java applications . It is most useful with object-oriented Domain Model and business logic in the Java-based middle-tier. Hibernate may not be the best solution for data-centric applications that only use stored-procedures to implement the business logic in the database. Hibernate is most suitable for applications based on a rich Domain Model involving complex interaction between entities
  • 8. Installation Download the latest version of Hibernate(e.g. hibernate-3.0.5.zip) from the site http://www.hibernate.org 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 Set the class path to include the necessary jar files and the configuration files
  • 9. Configuration Files Hibernate uses 3 configuration files during runtime, these files need to be present in its Class path :- hibernate.cfg.xml : Configuration of properties (both related and not related to Hibernate).Contains the ORM Mapping file names hibernate.properties : Configuration of properties (both related and not related to Hibernate). 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
  • 10. hibernate.cfg.xml Example <hibernate-configuration> <session-factory> <property name= connection.datasource&quot;>java:comp/env/jdbc/quickstart </property> <property name=&quot;show_sql&quot;>false</property> <property name=&quot;dialect&quot;>org.hibernate.dialect.PostgreSQLDialect </property> <!-- Mapping files --> <mapping resource=&quot;Cat.hbm.xml&quot;/> </session-factory> </hibernate-configuration>
  • 11. hibernate.cfg.xml Hibernate XML-based configuration.to know the the JDBC connection parameter(the other approach being the properties file) 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. The element (resource mapping ) provides the name of the ORM mapping file(s) for the persistent classes of the application
  • 12. hibernate.properties Please find the attached template of the property file
  • 13. Application .hbm.xml Example <hibernate-mapping> <class name=&quot;Event&quot; table=&quot;EVENTS&quot;> <id name=&quot;id&quot; column=&quot;EVENT_ID&quot;> </id> <property name=&quot;dateโ€œ type=&quot;timestamp&quot;column=&quot;EVENT_DATE&quot;/> <property name=&quot;title&quot;/> </class> <class name=โ€œPerson&quot; table=โ€œPERSON&quot;> โ€ฆ . </class> </hibernate-mapping>
  • 14. Exercise 1 & Exercise 2
  • 16. Core Interfaces 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 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 . Session Interface: A single-threaded, short-lived object representing a conversation between the application and the persistent store.
  • 17. Core Interfaces Transaction Interface : Optional interface to manage transactions.Hibernate applications may choose not to use this interface, instead manage transactions through their infrastructure code. Query Interface : This allows the developer to perform queries against the database and control how the query is executed
  • 18. States of an Instance Instances(of Persistent Classes ) may exist in one of three states: T ransient :The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value). 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 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.
  • 19. States of an Instance Example: Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); Person aPerson = (Person) session.load(Person.class, personId); Event anEvent = (Event) session.load(Event.class, eventId); tx.commit(); HibernateUtil.closeSession(); aPerson.getEvents().add(anEvent); // aPerson is detached Session session2 = HibernateUtil.currentSession(); Transaction tx2 = session.beginTransaction(); session2.update(aPerson); // Reattachment of aPerson tx2.commit(); HibernateUtil.closeSession();
  • 21. Basic O/R Mapping Object/relational mappings are defined in an XML document. The mapping language is Java-centric, meaning that mappings are constructed around persistent class declarations, not table declarations. A number of tools exist to generate the mapping document, including XDoclet, Middlegen and AndroMDA.
  • 22. Element <hibernate-mapping> The root element in O/R mapping file.Contains the following attributes schema (optional): The name of a database schema. catalog (optional): The name of a database catalog. default-cascade (optional - defaults to none ): A default cascade style. package (optional): Specifies a package prefix to assume for unqualified class names in the mapping document. Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping)
  • 23. Element <class> You may declare a persistent class using the class element : 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. table (optional - defaults to the unqualified class name): The name of its database table. mutable (optional, defaults to true): Specifies that instances of the class are (not) mutable. Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping)
  • 24. Element <id> Mapped classes must declare the primary key column of the database tab: name (optional): The name of the identifier property. type (optional): A name that indicates the Hibernate type. column (optional - defaults to the property name): The name of the primary key column. There is an alternative <composite-id> declaration to allow access to legacy data with composite keys Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping)
  • 25. Element <property> Mapped classes must declare the primary key column of the database tab : name : the name of the property, with an initial lowercase letter. 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). type (optional): a name that indicates the Hibernate type. Get the complete list and more information on the attributes from Hibernate_reference.pdf(Basic O/R Mapping)
  • 27. Collection Hibernate supports all kinds of collection mappings, a <set> being most common. The other collection mapping include <list>, <map>, <bag> and <array> 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.
  • 28. Collection Mapping Example : <class name=&quot;Department&quot; table=&quot;DEPARTMENT&quot;> <id name=&quot;id&quot; column=&quot;DEPCODE&quot;> <generator class=&quot;increment&quot;/> </id> <property name=&quot;DeptName&quot; column=&quot;DNAME&quot;/> <set name=&quot;EMPLIST&quot;> <key column=&quot;DEPCODE&quot;/> <one-to-many column = &quot;DEPTID&quot; class=&quot;Employee&quot;/> </set> </class>
  • 29. Associations Associations refer to relationships between entities Using Hibernate, we can represent relationships of all cardinality,i.e. one-to-one, one-to-many,many-to-one and many-to-many A many-to-many association will result in a link or association table Hibernate supports polymorphic association
  • 32. HQL(Hibernate Query Language) Hibernate is equipped with an extremely powerful query language that (quite intentionally) looks very much like SQL HQL is fully object-oriented, understanding notions like inheritance,polymorphism and association. Queries are case-insensitive, except for names of Java classes and properties. 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.
  • 33. HQL example 1 E.g. Get a list of all the employees (Table : MASTER_EMPLOYEE) SQL :- select * from MASTER_EMPLOYEE EMP HQL :- from MASTER_EMPLOYEE EMP Programmatically :- Query q = session.createQuery(โ€œfrom MASTER_EMPLOYEE EMP โ€) ; List result = q.list();
  • 34. HQL example 2 E.g. Get a list of all the employees (Table : MASTER_EMPLOYEE) where D_CODE = โ€™00Aโ€™ SQL :- select * from MASTER_EMPLOYEE EMP where EMP.D_CODE = โ€™00Aโ€™ HQL Programmatically :- Query q = session.createQuery(โ€œfrom MASTER_EMPLOYEE EMP where EMP.D_CODE = :code โ€) ; q.setString(โ€œcodeโ€,โ€00Aโ€); List result = q.list();
  • 35. HQL example 3 E.g. Get a count of all the employees SQL :- select count(*) from MASTER_EMPLOYEE EMP HQL Programmatically :- Query q = session.createQuery(โ€œselect count(*) from MASTER_EMPLOYEE EMPโ€) ; List result = q.list(); 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 The supported aggregate functions are avg(...), sum(...), min(...), max(...) count(*) count(...), count(distinct ...), count(all...)
  • 36. HQL HQL provides several other features for data retrieval which include :- Sub querying Join types supported by ANSI SQL (e.g. inner join,left outer,etc) Polymorphic queries Ordering/groping Usage of Expressions [e.g. emp.name in ( โ€˜Rakesh', โ€˜Manish', โ€˜Dhiraj' )] Executing native SQL queries Using stored procedures for querying Refer to hibernate_reference.pdf(Chapters : HQL,Criteria Query,Native SQL)
  • 37. Appendix ThreadLocal : 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). Domain Model : An object model of the domain problem that incorporates both behavior and data [ BACK ]
  • 38. Appendix Transparent Persistence 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 [ BACK ] Persistent classes Classes in an application that implement the entities of the business problem (e.g. Customer and Order in an E-commerce application) [ BACK ]
  • 39. References URL www.hibernate.org Reference Material hibernate_reference.pdf(can be downloaded from the above site) Hibernate in Action(Christian Bauer & Gavin King) [ Incase of any doubts or queries about this presentation mail me at [email protected] ]

Editor's Notes

  • #4: Granularity refers to the relative size of object youโ€™re working with
  • #5: 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
  • #10: Properties can be configured using either file,i.e. hibernate.cfg.xml or hibernate.properties.If the same properties are specified in both the files the xml will take precedence
  • #17: The five core interfaces are used in every Hibernate application.Using these interfaces, one can store and retrieve persistent objects and control transaction
  • #18: The five core interfaces are used in every Hibernate application.Using these interfaces, one can store and retrieve persistent objects and control transaction
  • #19: Persistent classes are classes in an application that implement the entities of the business problem (e.g. Customer and Order in an E-commerce application)
  • #20: Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete(). Any instance returned by a get() or load() method is persistent. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge(). save() and persist() result in an SQL INSERT, delete() in an SQL DELETE and update() or merge() in an SQL UPDATE. Changes to persistent instances are detected at flush time and also result in an SQL UPDATE. saveOrUpdate() and replicate() result in either an INSERT or an UPDATE
  • #30: A polymorphic association is an association that may refer to instances of a subclass of the class that was explicitly specified in the mapping metadata. E.g. There could be a one to many relationship between a User and BillDetail entity, where BillDetail is an abstract class having subclasses CreditCard or Cheque