SlideShare une entreprise Scribd logo
1  sur  70
Object / Relational Mapping Using Hibernate



Copyright © 2007 Accenture. All rights reserved. Accenture, its logo, and High Performance Delivered are trademarks of Accenture.
Session Structure
•   Introduction
•   Why Hibernate?
•   Architecture
•   Hibernate Basics
•   Example Application
•   Transactions
•   Object States
•   O / R Mappings
•   Hibernate Query Language (HQL)
•   Improving Performance
•   Alternatives to Hibernate
•   Q&A

                                     2
Introduction
• This presentation will consist of some background information on
  Hibernate and some examples that show the basic functionality of
  Hibernate.

• Obviously, there is more than one way to use Hibernate.




                                                                     3
Introduction: O / R Mismatch
O / R Mismatch
• The correlation between object types to database tables is not usually
  one to one. In examining the differences and mismatches between
  object and relational systems, explore the simple object model below.




                                                                           4
Introduction: O / R Mismatch
• How should instances of objects in this model be persisted?




• Normalized for flexibility or denormalized for performance?
• How do you decide?
• What if the Customer database table existed before the object model?
  What would you have to do to your class/object design?

                                                                         5
Introduction: O / R Mismatch
• When working with object-oriented systems, there’s a mismatch
  between the object model and the relational database.
• How do we map one to the other?




                                                                  6
Introduction: O / R Mismatch
• How to map associations between objects?
   – References are directional, foreign keys are not.
   – Foreign keys can’t represent many-to-many associations.




                                                               7
Introduction: Approaches to ORM
• Why relational databases?
  – Flexible and robust approach
    to data management.
  – De-facto standard in software
    development.
• Why object-oriented models?
  – Business logic can be implemented in
    Java (opposed to stored procedures).
  – Allows for use of design patterns and
    concepts like polymorphism.
  – Improves code reuse and maintainability.

• Demand for mapping interaction!
                                               8
Introduction: Approaches to ORM
• Use Java serialization
   – Write application state to a file
   – Can only be accessed as a whole
   – Not possible to access single objects

• Object-oriented database systems
   – No complete query language implementation exists
   – Lacks necessary features




                                                        9
Introduction: Preferred Solution
• Use a Object-Relational Mapping System (e.g. Hibernate): Provides a
  simple API for storing and retrieving Java objects directly to and from
  the database.
• Non-intrusive: No need to follow specific rules or design patterns.
• Transparent: Your object model is unaware.




                                                                            10
Introduction: Persistent Framework
• What’s a persistent framework?
    - An ORM service that stores and retrieves objects into a relational
     database.
• So why do we need a persistence framework?
    - To avoid hard coding SQL into our Java applications.

• JDBC and SQL require Java programmers to be familiar with relational
  database details.
• Java programs are object-oriented (or at least should be) in nature
  whereas relational databases are tabular in nature.
• Persistent frameworks help alleviate the ORM “impedance mismatch.”
.

                                                                           11
Session Structure
•   Introduction
•   Why Hibernate?
•   Architecture
•   Hibernate Basics
•   Example Application
•   Transactions
•   Object States
•   O / R Mappings
•   Hibernate Query Language (HQL)
•   Improving Performance
•   Alternatives to Hibernate
•   Q&A

                                     12
Why Hibernate?
Hibernate is considered a persistent framework for Java!

•   Introduced to address the issues of Entity Beans.
•   Built on top of JNDI, JDBC, JTA.
•   Uses XML based configuration files for mapping.
•   Supports many databases like Sybase, Oracle, MySQL,other Object-
    Oriented Databases etc.
•   Makes for easy migration from one vendor database to another.
•   Generates the JDBC Code based on the underlying vendor database.
•   Hibernate APIs are very simple to learn and use.
•   Provides a powerful object query language known as Hibernate Query
    Language (HQL).

                                                                         13
Why Hibernate?: Features
•   Inheritance, polymorphism support
•   Custom data types
•   Collections
•   Uni and bi-directional entity associations
•   Transactions and concurrency
•   Caching
•   Connection pooling
•   HQL – Advanced Object Query Language etc.




                                                 14
Session Structure
•   Introduction
•   Why Hibernate?
•   Architecture
•   Hibernate Basics
•   Example Application
•   Transactions
•   Object States
•   O / R Mappings
•   Hibernate Query Language (HQL)
•   Improving Performance
•   Alternatives to Hibernate
•   Q&A

                                     15
Architecture
• Middleware that manages
  persistence.

• Provides an abstraction layer
  between the Persistence Layer
  and the database.




                                  16
Session Structure
•   Introduction
•   Why Hibernate?
•   Architecture
•   Hibernate Basics
•   Example Application
•   Transactions
•   Object States
•   O / R Mappings
•   Hibernate Query Language (HQL)
•   Improving Performance
•   Alternatives to Hibernate
•   Q&A

                                     17
Hibernate Basics

SessionFactory
• A threadsafe (immutable) cache
  of compiled mappings for a
  single database.
• A factory for Session.
• Expensive to create.




                                   18
Hibernate Basics
Session
• A single-threaded, short-lived
  object representing a conversation
  between the application and the
  persistent store.
• Wraps a JDBC connection.
• Factory for Transaction.
• Holds a mandatory (first-level)
  cache of persistent objects; used
  when navigating the object graph
  or looking up objects by identifier.


                                         19
Hibernate Basics
Persistent Objects and Collections
• Short-lived, single-threaded objects
  containing persistent state and
  business function.
• These might be ordinary
  JavaBeans/POJOs. The only special
  thing about them is that they are
  currently associated with (exactly
  one) Session.
• As soon as the Session is closed,
  they will be detached and free to use
  in Any application layer.

                                          20
Hibernate Basics
Transient Objects and Collections
• Instances of persistent classes that
  are not currently associated with a
  Session.
• They may have been instantiated
  by the application and not (yet)
  persisted or they may have been
  instantiated by a closed Session.




                                         21
Hibernate Basics
Transaction
• A single-threaded,
  short-lived object used by the
  application to specify atomic
  units of work.
• Abstracts application from
  underlying JDBC, JTA or CORBA
  transaction.
• Multiple transactions per Session.




                                       22
Hibernate Basics: Architecture API
Configuration :                                              Session :
•Is the first Hibernate object to be used.                   •Main interface to accomplish work with the database.
•Created once during application initialization              •objects are saved and retrieved through a Session.
•A Configuration object is used to create a                  •Is lightweight and inexpensive to create.
SessionFactory                                               •Is not thread safe.
                                                             •Used to create a Transaction object




 Session Factory :
 • It is a factory for Session objects
 •created during application start up
 •Is a thread safe object                                        Transaction :
 •Is created per database
                                                                 •Represents a unit of work with the database (and
                                                                 potentially other systems).
                                                                 •Handled by an underlying transaction manager


Query and Criteria objects are used to retrieve (and recreate)
persistent objects.

                                                                                                                     23
Session Structure
•   Introduction
•   Why Hibernate?
•   Architecture
•   Hibernate Basics
•   Example Application
•   Transactions
•   Object States
•   O / R Mappings
•   Hibernate Query Language (HQL)
•   Improving Performance
•   Alternatives to Hibernate
•   Q&A

                                     24
Example Application: The StudentManager




                                          25
Java Object




              26
Example Application: The StudentManager




                                          27
Hibernate Mapping Files
• Tells Hibernate which tables and columns to use to load and store
  objects.




                                                                      28
Example Application: The StudentManager




                                          29
Configuration: Config File




                             30
Example Application: The StudentManager




                                          31
The Configuration Object

• Represents a set of mapping files.
• Mapping files can be specified
  programmatically or through
  the Hibernate configuration file.
• Intended as a start-up time object.




                                        32
Session Structure
•   Introduction
•   Why Hibernate?
•   Architecture
•   Hibernate Basics
•   Example Application
•   Transactions
•   Object States
•   O / R Mappings
•   Hibernate Query Language (HQL)
•   Improving Performance
•   Alternatives to Hibernate
•   Q&A

                                     33
Transactions
• A set of database operations which must be executed in entirety or not
  at all.
• Should end either with a commit or a rollback.
• All communication with a database has to occur inside a transaction!




                                                                           34
Transactions
• Most common pattern is session-per-request.




                                                35
Session Structure
•   Introduction
•   Why Hibernate?
•   Architecture
•   Hibernate Basics
•   Example Application
•   Transactions
•   Object States
•   O / R Mappings
•   Hibernate Query Language (HQL)
•   Improving Performance
•   Alternatives to Hibernate
•   Q&A

                                     36
Object States: Transient & Persistent
Transient :
•An object is transient if it has just been instantiated using the
new operator.
•It is not associated with a Hibernate Session.
•Use the Hibernate Session to make an object persistent.




Persistent :
•A persistent instance has a representation in the
database and an identifier value.
•It might just have been saved or loaded.
•Definied in the scope of a Session.




                                                                     37
Object States: Detached
Detached :
•A detached instance is an object that has been
persistent, but its Session has been closed.
•The reference to the object is still valid, of course, and
the detached instance might even be modified in this
state.
•A detached instance can be reattached to a new Session
at a later point in time, making it (and all the
modifications) persistent again.


                                                     Sample Code :
                                                     Session session = sessionFactory.openSession();
                                                     Transaction transaction = session.beginTransaction();
                                                     BallPlayer p = (BallPlayer)session.get(BallPlayer.class, 1L);
                                                     transaction.commit();
                                                     session.close();

                                                     //p is now Detached
                                                     p.setNickname("Bambino"); //change is unsynchronized
                                                     session = sessionFactory.openSession(); //again open new session
                                                     transaction = session.beginTransaction();
                                                     //can also use session.saveOrUpdate() in method call below
                                                     session.update(p); //now new nickname is applied
                                                     transaction.commit();
                                                     session.close();
                                                                                                                     38
Object States: Complete Lifecycle
• A complete diagram of the lifecycle, given a description of the states
  and methods that transition
  the objects between states.




                                                                           39
Session Structure
•   Introduction
•   Why Hibernate?
•   Architecture
•   Hibernate Basics
•   Example Application
•   Transactions
•   Object States
•   O / R Mappings
•   Hibernate Query Language (HQL)
•   Improving Performance
•   Alternatives to Hibernate
•   Q&A

                                     40
O / R Mapping: Collection Mapping
• Collection properties must be declared as an interface type (Set, not
  HashSet).
• Hibernate provides built-in mapping for Set, Map, List, and more.
• May contain basic types, custom types and references to other
  Hibernate objects.
• Collections are represented by a collection table in the database:
   – Collection key: foreign key of owning object
   – Collection element: object in the collection




                                                                          41
O / R Mapping: Collection Mapping




                                    42
OR Mapping: Association Mapping
• Hibernate lets you easily specify all kinds of associations between
  objects:
   – Unidirectional one-to-many
   – Unidirectional many-to-many
   – Bi-directional one-to-many
   – Bi-directional many-to-many
• Representing associations with join tables makes the database
  schema cleaner.
• Nullable foreign keys is bad practice.




                                                                        43
O / R Mapping: Unidirectional (One-to-
Many)




                                         44
O / R Mapping: Unidirectional (Many-to-
Many)




                                          45
O / R Mapping: Bi-directional (One-to-
Many)




                                         46
O / R Mapping: Bi-directional (Many-to-
Many)




                                          47
O / R Mapping: The Inverse Property
  Explained
• Bi-directional associations must be updated on both sides in the Java
  code!
• Hibernate maps many-relationships with a join table.
• Hibernate must ignore one side to avoid constraint violations!
• Must be the many side for one-to-many, but doesn’t matter for many-to-
  many.




                                                                           48
O / R Mapping: Component Mapping
•   A component is an object saved as a value, not as a reference.
•   Saved directly – no need to declare interfaces or identifiers.
•   Required to define an empty constructor.
•   Shared references not supported.




                                                                     49
O / R Mapping: Component Mapping




                                   50
Session Structure
•   Introduction
•   Why Hibernate?
•   Architecture
•   Hibernate Basics
•   Example Application
•   Transactions
•   Object States
•   O / R Mappings
•   Hibernate Query Language (HQL)
•   Improving Performance
•   Alternatives to Hibernate
•   Q&A

                                     51
Hibernate Query Language (HQL): The
  Query Interface
• You need a query when you don’t know the identifiers of the objects
  you are looking for.
• Used mainly to execute Hibernate Query Language queries.
• Obtained from a Hibernate Session instance.
• Provides functionality for:
   – Parameter binding to named query parameters
   – Retrieving lists of objects or unique objects
   – Limiting the number of retrieved objects




                                                                        52
Hibernate Query Language (HQL)
• HQL is an object-oriented query language
   – Syntax has similarities to SQL
   – Not working against tables and columns, but objects!
• Understands object-oriented concepts like inheritance
• Has advanced features like:
   – Associations and joins
   – Polymorphic queries
   – Sub-queries
   – Expressions
• Reduces the size of queries



                                                            53
Hibernate Query Language (HQL)




                                 54
Hibernate Query Language (HQL)




                                 55
Hibernate Query Language (HQL):
Where Clause




                                  56
Hibernate Query Language (HQL):
Query Example




                                  57
Hibernate Query Language (HQL):
Query Example




                                  58
Session Structure
•   Introduction
•   Why Hibernate?
•   Architecture
•   Hibernate Basics
•   Example Application
•   Transactions
•   Object States
•   O / R Mappings
•   Hibernate Query Language (HQL)
•   Improving Performance
•   Alternatives to Hibernate
•   Q&A

                                     59
Improving Performance
Fetching strategies: Hibernate uses a fetching strategy to retrieve
associated objects if the application needs to navigate the association.
Fetch strategies can be declared in the O / R mapping metadata, or
overridden by a particular HQL or criteria query.

  –   Join fetching
  –   Select fetching
  –   Sub-select fetching
  –   Batch fetching




                                                                           60
Improving Performance




                        61
Improving Performance




                        62
Improving Performance
About Caching:
• All objects that are passed to methods save(), update() or
  saveOrUpdate() or those you get from load(), get(), list(), iterate() or
  scroll() will be saved into cache.
• Flush() is used to synchronize the object with database and evict() is
  used to delete it from cache.
• Contains() used to find whether the object belongs to the cache or not.
• Session.clear() used to delete all objects from the cache.
• Suppose the query wants to force a refresh of its query cache region,
  we should call Query.setCacheMode(CacheMode.REFRESH).




                                                                             63
Session Structure
•   Introduction
•   Why Hibernate?
•   Architecture
•   Hibernate Basics
•   Example Application
•   Transactions
•   Object States
•   O / R Mappings
•   Hibernate Query Language (HQL)
•   Improving Performance
•   Alternatives to Hibernate
•   Q&A

                                     64
Alternatives to Hibernate
• Other popular ORMs are:
   – iBatis
   – JPA
   – TopLink
• iBatis
   – You want to create your own SQL's and are willing to maintain them
   – Your environment is driven by relational data model
   – Needs SQL Statements to be coded in its Mapping files
   – Good when developer needs control over the SQL
• TopLink
   – Very similar and quite powerful but costs
   – Vendor lock-in

                                                                          65
Alternatives to Hibernate
• JPA – Java Persistence API
   – Java EE 5 ORM Solution
   – Part of EJB 3 Specification
   – Supported by all Java EE vendors
   – Designed based on popular ORM solutions like iBatis,JDO, TopLink
     including Hibernate
   – Replaces Entity Beans
   – It’s more of a specification; you can use any provider like TopLink,
     etc.
   – Depends on provider which may implement more than standard
     specification
   – JPA lags in defining Caching and other advanced features
   – Useful in case of standard Java based solution using Java EE
     platform                                                               66
Session Structure
•   Introduction
•   Why Hibernate?
•   Architecture
•   Hibernate Basics
•   Example Application
•   Transactions
•   Object States
•   O / R Mappings
•   Hibernate Query Language (HQL)
•   Improving Performance
•   Alternatives to Hibernate
•   Q&A

                                     67
Q&A




      Questions?




                   68
References
•   Christian Bauer and Gavin King: Hibernate in Action
•   James Elliot: Hibernate – A Developer’s notebook
•   Justin Gehtland, Bruce A. Tate: Better, Faster, Lighter Java
•   http://www.hibernate.org
•   http://www.hibernate-training-guide.com




                                                                   69
Thanks




  Thanks eveybody for attending this session.




                                                70

Contenu connexe

Tendances

Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaEdureka!
 
Node.js and the MySQL Document Store
Node.js and the MySQL Document StoreNode.js and the MySQL Document Store
Node.js and the MySQL Document StoreRui Quelhas
 
MySQL Connector/Node.js and the X DevAPI
MySQL Connector/Node.js and the X DevAPIMySQL Connector/Node.js and the X DevAPI
MySQL Connector/Node.js and the X DevAPIRui Quelhas
 
Big Challenges in Data Modeling: NoSQL and Data Modeling
Big Challenges in Data Modeling: NoSQL and Data ModelingBig Challenges in Data Modeling: NoSQL and Data Modeling
Big Challenges in Data Modeling: NoSQL and Data ModelingDATAVERSITY
 
Real World Experience: Integrating DB2 with XPages
Real World Experience: Integrating DB2 with XPagesReal World Experience: Integrating DB2 with XPages
Real World Experience: Integrating DB2 with XPagesSteve_Zavocki
 
Sterling for Windows Phone 7
Sterling for Windows Phone 7Sterling for Windows Phone 7
Sterling for Windows Phone 7Jeremy Likness
 
Leveraging Solr and Mahout
Leveraging Solr and MahoutLeveraging Solr and Mahout
Leveraging Solr and MahoutGrant Ingersoll
 
Datomic – A Modern Database - StampedeCon 2014
Datomic – A Modern Database - StampedeCon 2014Datomic – A Modern Database - StampedeCon 2014
Datomic – A Modern Database - StampedeCon 2014StampedeCon
 
Software Development: Beyond Training wheels
Software Development: Beyond Training wheelsSoftware Development: Beyond Training wheels
Software Development: Beyond Training wheelsNaveenkumar Muguda
 

Tendances (14)

Ajax Zf
Ajax ZfAjax Zf
Ajax Zf
 
Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | Edureka
 
Introduction to datomic
Introduction to datomicIntroduction to datomic
Introduction to datomic
 
Agile xml
Agile xmlAgile xml
Agile xml
 
Node.js and the MySQL Document Store
Node.js and the MySQL Document StoreNode.js and the MySQL Document Store
Node.js and the MySQL Document Store
 
Nosql data models
Nosql data modelsNosql data models
Nosql data models
 
MySQL Connector/Node.js and the X DevAPI
MySQL Connector/Node.js and the X DevAPIMySQL Connector/Node.js and the X DevAPI
MySQL Connector/Node.js and the X DevAPI
 
Odi ireland rittman
Odi ireland rittmanOdi ireland rittman
Odi ireland rittman
 
Big Challenges in Data Modeling: NoSQL and Data Modeling
Big Challenges in Data Modeling: NoSQL and Data ModelingBig Challenges in Data Modeling: NoSQL and Data Modeling
Big Challenges in Data Modeling: NoSQL and Data Modeling
 
Real World Experience: Integrating DB2 with XPages
Real World Experience: Integrating DB2 with XPagesReal World Experience: Integrating DB2 with XPages
Real World Experience: Integrating DB2 with XPages
 
Sterling for Windows Phone 7
Sterling for Windows Phone 7Sterling for Windows Phone 7
Sterling for Windows Phone 7
 
Leveraging Solr and Mahout
Leveraging Solr and MahoutLeveraging Solr and Mahout
Leveraging Solr and Mahout
 
Datomic – A Modern Database - StampedeCon 2014
Datomic – A Modern Database - StampedeCon 2014Datomic – A Modern Database - StampedeCon 2014
Datomic – A Modern Database - StampedeCon 2014
 
Software Development: Beyond Training wheels
Software Development: Beyond Training wheelsSoftware Development: Beyond Training wheels
Software Development: Beyond Training wheels
 

Similaire à 2010 05-21, object-relational mapping using hibernate v2

Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeApache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeAndrus Adamchik
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate BasicsDeeptiJava
 
What is Hibernate Framework?
What is Hibernate Framework?What is Hibernate Framework?
What is Hibernate Framework?Ducat India
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPagesToby Samples
 
Introduction to Object-Relational Mapping
Introduction to Object-Relational MappingIntroduction to Object-Relational Mapping
Introduction to Object-Relational MappingAli Shakiba
 
Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Wen-Tien Chang
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introductionSagar Verma
 
AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)Igor Talevski
 
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGMUsing JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGMPT.JUG
 

Similaire à 2010 05-21, object-relational mapping using hibernate v2 (20)

Hibernate
HibernateHibernate
Hibernate
 
Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeApache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM Alternative
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
Hibernate
HibernateHibernate
Hibernate
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate Basics
 
What is Hibernate Framework?
What is Hibernate Framework?What is Hibernate Framework?
What is Hibernate Framework?
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
 
Hibernate
HibernateHibernate
Hibernate
 
Dao benchmark
Dao benchmarkDao benchmark
Dao benchmark
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPages
 
Java Spring
Java SpringJava Spring
Java Spring
 
Introduction to Object-Relational Mapping
Introduction to Object-Relational MappingIntroduction to Object-Relational Mapping
Introduction to Object-Relational Mapping
 
Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
Persistence hibernate
Persistence hibernatePersistence hibernate
Persistence hibernate
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
J2EE Online Training
J2EE Online TrainingJ2EE Online Training
J2EE Online Training
 
AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)
 
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGMUsing JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
 

Plus de alvaro alcocer sotil (20)

Clase ciencia - Huesos
Clase ciencia - HuesosClase ciencia - Huesos
Clase ciencia - Huesos
 
Rm rompecabeza
Rm rompecabezaRm rompecabeza
Rm rompecabeza
 
Locomocion en animales
Locomocion en animalesLocomocion en animales
Locomocion en animales
 
Presentacion comuniccaion
Presentacion comuniccaionPresentacion comuniccaion
Presentacion comuniccaion
 
El trabajo académico chomsky
El trabajo académico chomskyEl trabajo académico chomsky
El trabajo académico chomsky
 
[002665]
[002665][002665]
[002665]
 
Catedral de-lima-historia-nc2ba-51-pps
Catedral de-lima-historia-nc2ba-51-ppsCatedral de-lima-historia-nc2ba-51-pps
Catedral de-lima-historia-nc2ba-51-pps
 
Proceso de ventas 2013
Proceso de ventas 2013Proceso de ventas 2013
Proceso de ventas 2013
 
Royal plaza
Royal plazaRoyal plaza
Royal plaza
 
Plan de marketing
Plan de marketingPlan de marketing
Plan de marketing
 
Intercambio de publicidad
Intercambio de publicidadIntercambio de publicidad
Intercambio de publicidad
 
Producto marca
Producto   marcaProducto   marca
Producto marca
 
Plan de mk tcompleto (3)
Plan de mk tcompleto (3)Plan de mk tcompleto (3)
Plan de mk tcompleto (3)
 
La marca debe ser humana
La marca debe ser humanaLa marca debe ser humana
La marca debe ser humana
 
3º sesion la competencia
3º sesion la competencia3º sesion la competencia
3º sesion la competencia
 
2ºsesion beneficios de la planeacion de marketing
2ºsesion beneficios de la planeacion de marketing2ºsesion beneficios de la planeacion de marketing
2ºsesion beneficios de la planeacion de marketing
 
1º sesion planeamiento estratégico de marketing
1º sesion planeamiento estratégico de marketing1º sesion planeamiento estratégico de marketing
1º sesion planeamiento estratégico de marketing
 
Aprendiendo publicidad ppt final paola
Aprendiendo publicidad ppt final paolaAprendiendo publicidad ppt final paola
Aprendiendo publicidad ppt final paola
 
Agencia de publicidad la campaña publicitaria -tipos
Agencia de  publicidad   la campaña publicitaria -tiposAgencia de  publicidad   la campaña publicitaria -tipos
Agencia de publicidad la campaña publicitaria -tipos
 
10º
 10º 10º
10º
 

Dernier

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Dernier (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

2010 05-21, object-relational mapping using hibernate v2

  • 1. Object / Relational Mapping Using Hibernate Copyright © 2007 Accenture. All rights reserved. Accenture, its logo, and High Performance Delivered are trademarks of Accenture.
  • 2. Session Structure • Introduction • Why Hibernate? • Architecture • Hibernate Basics • Example Application • Transactions • Object States • O / R Mappings • Hibernate Query Language (HQL) • Improving Performance • Alternatives to Hibernate • Q&A 2
  • 3. Introduction • This presentation will consist of some background information on Hibernate and some examples that show the basic functionality of Hibernate. • Obviously, there is more than one way to use Hibernate. 3
  • 4. Introduction: O / R Mismatch O / R Mismatch • The correlation between object types to database tables is not usually one to one. In examining the differences and mismatches between object and relational systems, explore the simple object model below. 4
  • 5. Introduction: O / R Mismatch • How should instances of objects in this model be persisted? • Normalized for flexibility or denormalized for performance? • How do you decide? • What if the Customer database table existed before the object model? What would you have to do to your class/object design? 5
  • 6. Introduction: O / R Mismatch • When working with object-oriented systems, there’s a mismatch between the object model and the relational database. • How do we map one to the other? 6
  • 7. Introduction: O / R Mismatch • How to map associations between objects? – References are directional, foreign keys are not. – Foreign keys can’t represent many-to-many associations. 7
  • 8. Introduction: Approaches to ORM • Why relational databases? – Flexible and robust approach to data management. – De-facto standard in software development. • Why object-oriented models? – Business logic can be implemented in Java (opposed to stored procedures). – Allows for use of design patterns and concepts like polymorphism. – Improves code reuse and maintainability. • Demand for mapping interaction! 8
  • 9. Introduction: Approaches to ORM • Use Java serialization – Write application state to a file – Can only be accessed as a whole – Not possible to access single objects • Object-oriented database systems – No complete query language implementation exists – Lacks necessary features 9
  • 10. Introduction: Preferred Solution • Use a Object-Relational Mapping System (e.g. Hibernate): Provides a simple API for storing and retrieving Java objects directly to and from the database. • Non-intrusive: No need to follow specific rules or design patterns. • Transparent: Your object model is unaware. 10
  • 11. Introduction: Persistent Framework • What’s a persistent framework? - An ORM service that stores and retrieves objects into a relational database. • So why do we need a persistence framework? - To avoid hard coding SQL into our Java applications. • JDBC and SQL require Java programmers to be familiar with relational database details. • Java programs are object-oriented (or at least should be) in nature whereas relational databases are tabular in nature. • Persistent frameworks help alleviate the ORM “impedance mismatch.” . 11
  • 12. Session Structure • Introduction • Why Hibernate? • Architecture • Hibernate Basics • Example Application • Transactions • Object States • O / R Mappings • Hibernate Query Language (HQL) • Improving Performance • Alternatives to Hibernate • Q&A 12
  • 13. Why Hibernate? Hibernate is considered a persistent framework for Java! • Introduced to address the issues of Entity Beans. • Built on top of JNDI, JDBC, JTA. • Uses XML based configuration files for mapping. • Supports many databases like Sybase, Oracle, MySQL,other Object- Oriented Databases etc. • Makes for easy migration from one vendor database to another. • Generates the JDBC Code based on the underlying vendor database. • Hibernate APIs are very simple to learn and use. • Provides a powerful object query language known as Hibernate Query Language (HQL). 13
  • 14. Why Hibernate?: Features • Inheritance, polymorphism support • Custom data types • Collections • Uni and bi-directional entity associations • Transactions and concurrency • Caching • Connection pooling • HQL – Advanced Object Query Language etc. 14
  • 15. Session Structure • Introduction • Why Hibernate? • Architecture • Hibernate Basics • Example Application • Transactions • Object States • O / R Mappings • Hibernate Query Language (HQL) • Improving Performance • Alternatives to Hibernate • Q&A 15
  • 16. Architecture • Middleware that manages persistence. • Provides an abstraction layer between the Persistence Layer and the database. 16
  • 17. Session Structure • Introduction • Why Hibernate? • Architecture • Hibernate Basics • Example Application • Transactions • Object States • O / R Mappings • Hibernate Query Language (HQL) • Improving Performance • Alternatives to Hibernate • Q&A 17
  • 18. Hibernate Basics SessionFactory • A threadsafe (immutable) cache of compiled mappings for a single database. • A factory for Session. • Expensive to create. 18
  • 19. Hibernate Basics Session • A single-threaded, short-lived object representing a conversation between the application and the persistent store. • Wraps a JDBC connection. • Factory for Transaction. • Holds a mandatory (first-level) cache of persistent objects; used when navigating the object graph or looking up objects by identifier. 19
  • 20. Hibernate Basics Persistent Objects and Collections • Short-lived, single-threaded objects containing persistent state and business function. • These might be ordinary JavaBeans/POJOs. The only special thing about them is that they are currently associated with (exactly one) Session. • As soon as the Session is closed, they will be detached and free to use in Any application layer. 20
  • 21. Hibernate Basics Transient Objects and Collections • Instances of persistent classes that are not currently associated with a Session. • They may have been instantiated by the application and not (yet) persisted or they may have been instantiated by a closed Session. 21
  • 22. Hibernate Basics Transaction • A single-threaded, short-lived object used by the application to specify atomic units of work. • Abstracts application from underlying JDBC, JTA or CORBA transaction. • Multiple transactions per Session. 22
  • 23. Hibernate Basics: Architecture API Configuration : Session : •Is the first Hibernate object to be used. •Main interface to accomplish work with the database. •Created once during application initialization •objects are saved and retrieved through a Session. •A Configuration object is used to create a •Is lightweight and inexpensive to create. SessionFactory •Is not thread safe. •Used to create a Transaction object Session Factory : • It is a factory for Session objects •created during application start up •Is a thread safe object Transaction : •Is created per database •Represents a unit of work with the database (and potentially other systems). •Handled by an underlying transaction manager Query and Criteria objects are used to retrieve (and recreate) persistent objects. 23
  • 24. Session Structure • Introduction • Why Hibernate? • Architecture • Hibernate Basics • Example Application • Transactions • Object States • O / R Mappings • Hibernate Query Language (HQL) • Improving Performance • Alternatives to Hibernate • Q&A 24
  • 25. Example Application: The StudentManager 25
  • 27. Example Application: The StudentManager 27
  • 28. Hibernate Mapping Files • Tells Hibernate which tables and columns to use to load and store objects. 28
  • 29. Example Application: The StudentManager 29
  • 31. Example Application: The StudentManager 31
  • 32. The Configuration Object • Represents a set of mapping files. • Mapping files can be specified programmatically or through the Hibernate configuration file. • Intended as a start-up time object. 32
  • 33. Session Structure • Introduction • Why Hibernate? • Architecture • Hibernate Basics • Example Application • Transactions • Object States • O / R Mappings • Hibernate Query Language (HQL) • Improving Performance • Alternatives to Hibernate • Q&A 33
  • 34. Transactions • A set of database operations which must be executed in entirety or not at all. • Should end either with a commit or a rollback. • All communication with a database has to occur inside a transaction! 34
  • 35. Transactions • Most common pattern is session-per-request. 35
  • 36. Session Structure • Introduction • Why Hibernate? • Architecture • Hibernate Basics • Example Application • Transactions • Object States • O / R Mappings • Hibernate Query Language (HQL) • Improving Performance • Alternatives to Hibernate • Q&A 36
  • 37. Object States: Transient & Persistent Transient : •An object is transient if it has just been instantiated using the new operator. •It is not associated with a Hibernate Session. •Use the Hibernate Session to make an object persistent. Persistent : •A persistent instance has a representation in the database and an identifier value. •It might just have been saved or loaded. •Definied in the scope of a Session. 37
  • 38. Object States: Detached Detached : •A detached instance is an object that has been persistent, but its Session has been closed. •The reference to the object is still valid, of course, and the detached instance might even be modified in this state. •A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. Sample Code : Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); BallPlayer p = (BallPlayer)session.get(BallPlayer.class, 1L); transaction.commit(); session.close(); //p is now Detached p.setNickname("Bambino"); //change is unsynchronized session = sessionFactory.openSession(); //again open new session transaction = session.beginTransaction(); //can also use session.saveOrUpdate() in method call below session.update(p); //now new nickname is applied transaction.commit(); session.close(); 38
  • 39. Object States: Complete Lifecycle • A complete diagram of the lifecycle, given a description of the states and methods that transition the objects between states. 39
  • 40. Session Structure • Introduction • Why Hibernate? • Architecture • Hibernate Basics • Example Application • Transactions • Object States • O / R Mappings • Hibernate Query Language (HQL) • Improving Performance • Alternatives to Hibernate • Q&A 40
  • 41. O / R Mapping: Collection Mapping • Collection properties must be declared as an interface type (Set, not HashSet). • Hibernate provides built-in mapping for Set, Map, List, and more. • May contain basic types, custom types and references to other Hibernate objects. • Collections are represented by a collection table in the database: – Collection key: foreign key of owning object – Collection element: object in the collection 41
  • 42. O / R Mapping: Collection Mapping 42
  • 43. OR Mapping: Association Mapping • Hibernate lets you easily specify all kinds of associations between objects: – Unidirectional one-to-many – Unidirectional many-to-many – Bi-directional one-to-many – Bi-directional many-to-many • Representing associations with join tables makes the database schema cleaner. • Nullable foreign keys is bad practice. 43
  • 44. O / R Mapping: Unidirectional (One-to- Many) 44
  • 45. O / R Mapping: Unidirectional (Many-to- Many) 45
  • 46. O / R Mapping: Bi-directional (One-to- Many) 46
  • 47. O / R Mapping: Bi-directional (Many-to- Many) 47
  • 48. O / R Mapping: The Inverse Property Explained • Bi-directional associations must be updated on both sides in the Java code! • Hibernate maps many-relationships with a join table. • Hibernate must ignore one side to avoid constraint violations! • Must be the many side for one-to-many, but doesn’t matter for many-to- many. 48
  • 49. O / R Mapping: Component Mapping • A component is an object saved as a value, not as a reference. • Saved directly – no need to declare interfaces or identifiers. • Required to define an empty constructor. • Shared references not supported. 49
  • 50. O / R Mapping: Component Mapping 50
  • 51. Session Structure • Introduction • Why Hibernate? • Architecture • Hibernate Basics • Example Application • Transactions • Object States • O / R Mappings • Hibernate Query Language (HQL) • Improving Performance • Alternatives to Hibernate • Q&A 51
  • 52. Hibernate Query Language (HQL): The Query Interface • You need a query when you don’t know the identifiers of the objects you are looking for. • Used mainly to execute Hibernate Query Language queries. • Obtained from a Hibernate Session instance. • Provides functionality for: – Parameter binding to named query parameters – Retrieving lists of objects or unique objects – Limiting the number of retrieved objects 52
  • 53. Hibernate Query Language (HQL) • HQL is an object-oriented query language – Syntax has similarities to SQL – Not working against tables and columns, but objects! • Understands object-oriented concepts like inheritance • Has advanced features like: – Associations and joins – Polymorphic queries – Sub-queries – Expressions • Reduces the size of queries 53
  • 56. Hibernate Query Language (HQL): Where Clause 56
  • 57. Hibernate Query Language (HQL): Query Example 57
  • 58. Hibernate Query Language (HQL): Query Example 58
  • 59. Session Structure • Introduction • Why Hibernate? • Architecture • Hibernate Basics • Example Application • Transactions • Object States • O / R Mappings • Hibernate Query Language (HQL) • Improving Performance • Alternatives to Hibernate • Q&A 59
  • 60. Improving Performance Fetching strategies: Hibernate uses a fetching strategy to retrieve associated objects if the application needs to navigate the association. Fetch strategies can be declared in the O / R mapping metadata, or overridden by a particular HQL or criteria query. – Join fetching – Select fetching – Sub-select fetching – Batch fetching 60
  • 63. Improving Performance About Caching: • All objects that are passed to methods save(), update() or saveOrUpdate() or those you get from load(), get(), list(), iterate() or scroll() will be saved into cache. • Flush() is used to synchronize the object with database and evict() is used to delete it from cache. • Contains() used to find whether the object belongs to the cache or not. • Session.clear() used to delete all objects from the cache. • Suppose the query wants to force a refresh of its query cache region, we should call Query.setCacheMode(CacheMode.REFRESH). 63
  • 64. Session Structure • Introduction • Why Hibernate? • Architecture • Hibernate Basics • Example Application • Transactions • Object States • O / R Mappings • Hibernate Query Language (HQL) • Improving Performance • Alternatives to Hibernate • Q&A 64
  • 65. Alternatives to Hibernate • Other popular ORMs are: – iBatis – JPA – TopLink • iBatis – You want to create your own SQL's and are willing to maintain them – Your environment is driven by relational data model – Needs SQL Statements to be coded in its Mapping files – Good when developer needs control over the SQL • TopLink – Very similar and quite powerful but costs – Vendor lock-in 65
  • 66. Alternatives to Hibernate • JPA – Java Persistence API – Java EE 5 ORM Solution – Part of EJB 3 Specification – Supported by all Java EE vendors – Designed based on popular ORM solutions like iBatis,JDO, TopLink including Hibernate – Replaces Entity Beans – It’s more of a specification; you can use any provider like TopLink, etc. – Depends on provider which may implement more than standard specification – JPA lags in defining Caching and other advanced features – Useful in case of standard Java based solution using Java EE platform 66
  • 67. Session Structure • Introduction • Why Hibernate? • Architecture • Hibernate Basics • Example Application • Transactions • Object States • O / R Mappings • Hibernate Query Language (HQL) • Improving Performance • Alternatives to Hibernate • Q&A 67
  • 68. Q&A Questions? 68
  • 69. References • Christian Bauer and Gavin King: Hibernate in Action • James Elliot: Hibernate – A Developer’s notebook • Justin Gehtland, Bruce A. Tate: Better, Faster, Lighter Java • http://www.hibernate.org • http://www.hibernate-training-guide.com 69
  • 70. Thanks Thanks eveybody for attending this session. 70

Notes de l'éditeur

  1. Speaker’s notes: First level cache takes care of giving the application the same java object each time the corresponding persistent object is accessed Cache strategy may be typically read-only, read-write etc. It can be set per class. Second-level cache can be per JVM, on disc or clustered (ip-multicast)