Object-Relational Mapping with Hibernate Brian Sam-Bodden Principal Partner Integrallis Software, LLC. August 1 - 5, 2005.

Slides:



Advertisements
Similar presentations
Introduction to NHibernate By Andrew Smith. The Basics Object Relation Mapper Maps POCOs to database tables Based on Java Hibernate. V stable Generates.
Advertisements

An Object/Relational Mapping tool Free and open source Simplifies storage of object data in a relational database Removes the need to write and maintain.
Spring, Hibernate and Web Services 13 th September 2014.
.NET Database Technologies: Open-Source Frameworks.
Hibernate 1. Introduction ORM goal: Take advantage of the things SQL databases do well, without leaving the Java language of objects and classes. ORM.
© 2005, Cornell University. Rapid Application Development using the Kuali Architecture (Struts, Spring and OJB) A Case Study Bryan Hutchinson
ODBC and JDBC O/R Mapping David Rabinowitz. June 2nd, 2004 Object Oriented Design Course 2 Objects And Databases Most of the applications today are written.
ODBC and JDBC O/R Mapping Amit Shabtay. June 2nd, 2004 Object Oriented Design Course 2 Objects And Databases Most of the applications today are written.
ORM Object-Relational Mapping 1. Object Persistence Persistence is the ability of an object to survive the lifecycle of the process, in which it resides.
Session-02.
Session-01. Hibernate Framework ? Why we use Hibernate ?
An Introduction to Hibernate Matt Secoske
Data Persistence and Object-Relational Mapping Slides by James Brucker, used with his permission 1.
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
Enterprise Object Framework. What is EOF? Enterprise Objects Framework is a set of tools and resources that help you create applications that work with.
Rapid Persistence Layer Development with Hibernate Rapid Persistence Layer Development with Hibernate Tyler Mendenhall E-gineering,
1 INTRO TO BUSINESS COMPONENTS FOR JAVA (BC4J) Matt Fierst Computer Resource Team OracleWorld Session
Agenda What is Hibernate Spring Integration Questions Overview
Maven for building Java applications By Nalin De Zoysa
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
Data Access Patterns Some of the problems with data access from OO programs: 1.Data source and OO program use different data modelling concepts 2.Decoupling.
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
Entity Beans BMP Celsina Bignoli
Object persistence with Hibernate in Decision Deck 1.1 Gilles Dodinet 2 nd Decision Deck Workshop 2008, February.
JBoss Cache. Cache A place to temporarily store data that is expensive or difficult to compute or retrieve. Caches should be fast to access. May or may.
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
Hibernate Query Language Make SQL be object oriented – Classes and properties instead of tables and columns – Polymorphism – Associations – Much less verbose.
Seminar on. Overview Hibernate. What is it? Hibernate. How does it work? Hibernate Tools.
Geodatabase Relationships & Relationship Classes GIS 458 Spring 2006 Larry Clamp.
Object/Relational Mapping with Hibernate Practical ORM.
CS 157B: Database Management Systems II February 6 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
Object Oriented Analysis and Design 1 Chapter 7 Database Design  UML Specification for Data Modeling  The Relational Data Model and Object Model  Persistence.
1 Part 2: EJB Persistency Jianguo Lu. 2 Object Persistency A persistent object is one that can automatically store and retrieve itself in permanent storage.
© 2011 Pearson Education, Inc. Publishing as Prentice Hall 1 Chapter 14 Using Relational Databases to Provide Object Persistence (Overview) Modern Database.
Hibernate Persistence. What is Persistence Persist data to database or other storage.  In OO world, persistence means persist object to external storage.
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
Domain and Persistence Patterns. Fundamental Pattern Types Design Patterns Business Logic Patterns.
Hibernate Introduction - 1 Present by Eric Yu. BeanSoft | 2 Content Understanding object/relational persistence Introduction Architecture The core interfaces.
Chapter 38 Persistence Framework with Patterns 1CS6359 Fall 2011 John Cole.
Java Data Persistence Using Hibernate Jack Gardner October 2004.
An Introduction to Object/Relational Persistence and Hibernate Yi Li
A U.S. Department of Energy Office of Science Laboratory Operated by The University of Chicago Argonne National Laboratory Office of Science U.S. Department.
JPA / HIBERNATE CSCI 6370 Nilayan Bhattacharya Sanket Sable.
Fall CIS 764 Database Systems Engineering L18.2 : Object Relational Mapping … ….Object persistence.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
Hibernate Basics. Basics What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch.  The Problem of Granularity.  The Problem.
Chapter 18 Object Database Management Systems. Outline Motivation for object database management Object-oriented principles Architectures for object database.
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February
Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Introduction – ORM, Helloworld Application
Hibernate Thuy, Le Huu. Pentalog VN. Agenda Hibernate Annotations Improving performance – Lazy loading – Fetching Strategies – Dynamic insert, dynamic.
Singleton Academy, Pune. Course syllabus Singleton Academy Pune – Course Syllabus1.
Google Code Libraries Dima Ionut Daniel. Contents What is Google Code? LDAPBeans Object-ldap-mapping Ldap-ODM Bug4j jOOR Rapa jongo Conclusion Bibliography.
CS422 Principles of Database Systems Object-Relational Mapping (ORM) Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA (I) Chengyu Sun California State University, Los Angeles.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
Hibernate Online Training. Introduction to Hibernate Hibernate is a high-performance Object-Relational persistence and query service which takes care.
Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves the developer from common data persistence.
Hibernate Java Persistence API. What is Persistence Persistence: The continued or prolonged existence of something. Most Applications Achieve Persistence.
HIBERNATE/Java Overview of technology for Hibernate by محمد حسن کاظمی پوران Master : M.M.Nematollahi.
Don't Know Jack About Object-Relational Mapping?
Chengyu Sun California State University, Los Angeles
Object/Relational Mapping with Hibernate
Java Data Persistence Using Hibernate
Database Applications (15-415) ORM - Part I Lecture 11, February 11, 2018 Mohammad Hammoud.
Hibernate Bayu Priyambadha, S.Kom.
Developing and testing enterprise Java applications
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Object-Relational Mapping with Hibernate Brian Sam-Bodden Principal Partner Integrallis Software, LLC. August 1 - 5, 2005

Contents The Problem Object-Relational Mapping Hibernate Core Concepts Hibernate Architecture Hibernate Mappings Configuring Hibernate Working with Persistent Objects Persistence Lifecycle

Contents Working with Collections More on Association Mappings HQL – The Hibernate Query Language Query by Criteria Query by Example Caching Other Hibernate Features Conclusions

The Problem Two Different Worlds Object-Oriented Systems Represent a problem in terms of objects Semantically richer, encapsulate data and behavior Relational Databases Efficient data storage, retrieval and integrity of the data Provide a “normalized” set of data

Early on in a system’s life, both models tend to look alike As the system matures two models diverge They grow to do what they do best –Object model gets richer –Data model changes to accommodate operational factors The Problem Natural Divergence

The Problem Object-Relational Mismatch Granularity –Object Oriented vs. Database Types –User-Defined Column Types (UDT) are not portable Inheritance & Polymorphism –Not supported in the relational model –No polymorphic queries –Columns are strictly typed

The Problem Object-Relational Mismatch Identity Mismatch –Object Identity vs. Object Equality –Different objects can map to the same column or columns –Database Identity Strategies –Natural Keys versus Surrogate Keys

The Problem Object-Relational Mismatch Associations –Object References versus Foreign Keys –Directionality of Associations –Tables associations are always one- to-many or many-to-one –Object associations can be many-to- many

The Problem Object-Relational Mismatch Object Graph Navigation –Object-oriented applications “walk” the object graph –Object-oriented systems access what they need –With database we need a “plan” of what to retrieve –N+1 Problem is a common symptom

Object-Relational Mapping Tools/techniques to store and retrieve objects from a database From the code perspective it behaves like a virtual object database A complete ORM solution should provide: –Basic CRUD functionality –An Object-Oriented Query Facility –Mapping Metadata support –Transactional Capability

Hibernate Relational Persistence For Idiomatic Java Provides –Transparent persistence –Object-querying capabilities –Caching Works with fine-grained POJO-based models Supports most Databases Created by Gavin King, now part of the JBoss Group

Hibernate Relational Persistence For Idiomatic Java Declarative programming Uses Runtime Reflection Query Language is SQL-like –Leverages programmer’s knowledge Mappings –Typically defined as XML documents But you never have to write XML if you don’t want to (XDoclet, JSE 1.5 Annots)

Hibernate Relational Persistence For Idiomatic Java

Hibernate Core Concepts Session Factory –is a cache of compiled mappings for a single database. –used to retrieve Hibernate Sessions Session –Short lived Temporary bridge between the app and the data storage –Provides CRUD operations on Objects –Wraps a JDBC Connection / J2EE Data Source –Serves as a first level object cache

Architecture

Architecture Choices How much you use depends on your needs –Lightweight Basic persistence –Fully Integrated Transactions Caching Connection Pooling

O/R Mappings Hibernate Mapping (.hbm.xml) Files define: –Column to Field Mappings –Primary Key mapping & generation Scheme –Associations –Collections –Caching Settings –Custom SQL –And many more settings…

HBM XML File <hibernate-mapping package="com.integrallis.techconf.domain"> …

O/R Mappings Hibernate uses smart defaults Mapping files can be generated: –Manually Tedious, boring and error prone Total control of the mapping –From POJOs XDoclet, Annotations –From Database Schema Middlegen, Synchronizer, Hibernate Tools

Configuring Hibernate Hibernate Session Factory configured via hibernate.cfg.xml CFG file determines which mappings to load (.hbm.xml files) In your application SessionFactory is a singleton You request a Session as needed to work with persistent objects

The Big Picture

Working with Persistent Objects Saving an Object Address address = new Address();... Session session = null; Transaction tx = null; try { session = factory.openSession(); tx = session.beginTransaction(); session.save( address ); tx.commit(); … } finally { session.close(); } POJO is created Start a Session Transaction is started The object is saved The transaction is committed The session is closed

Working with Persistent Objects Loading an Object Address address = null; Session session = null; session = factory.openSession(); try { address = (Address) session.get(Address.class, id); } finally { session.close(); } Start a Session POJO is loaded PK and Object Class are provided The session is closed

Working with Persistent Objects Deleting an Object Session session = null; Transaction tx = null; try { session = factory.openSession(); tx = session.beginTransaction(); session.delete( address ); tx.commit(); … } finally { session.close(); } Start a Session Transaction is started The object is deleted The transaction is committed The session is closed

Persistence Lifecycle Possible States Transient –Not Associated with a database table –Non-transactional Persisted –Object with Database Identity –Associates object with a Session –Transactional Detached –no longer guaranteed to be in synch with the database

Persistence Lifecycle

Working with Collections Can represent a parent-child/one-many relationship using most of the available Java Collections Persistence by reach-ability No added semantics to your collections Available Collection mappings are –,,,, and In the database mappings are defined by a foreign key to the owning/parent entity

Working with Collections A simple example

public class Conference implements Serializable {... // Tracks belonging to this Conference private Set tracks ; public Set getTracks () { return tracks ; } public void setTracks (Set tracks) { this. tracks = tracks; } // maintain bi-directional association public void addTrack(Track track ) { if (null == tracks ) tracks = new HashSet(); track.setConference(this); tracks.add( track ); }

Working with Collections A simple example <id column=" PK_ID " name=" Id “ type="integer">... <set name=" Tracks " inverse="true" cascade="all" lazy="false"> Class/Table How to generate PK Other field mappings Java Set for the Tracks Class on the many side Foreign Key on the many side

Association Mappings Supported Associations One-to-one –Maintained with Foreign Keys in Database One-to-many / Many-to-one –Object on the ‘one’ side –Collection on the many ‘side’ Many-to-Many –Use a ‘mapping’ table in the database

Association Mappings Some Details Inverse attribute used for bi-directional associations Lazy Loading –Configured per relationship –Uses dynamic proxies at Runtime Cascading Styles – “none” no operations are cascaded – “all” all operations are cascaded –Every operation in Hibernate has a corresponding cascade style

Hibernate Query Language HQL An objectified version of SQL –Polymorphic Queries –Object parameters in Queries –Less verbose than SQL Doesn’t hide the power of SQL –SQL joins, Cartesian products –Projections –Aggregation (max, avg) and grouping –Ordering –Sub-queries –…and more

Hibernate Query Language HQL Simplest HQL Query –Return all Addresses session = sessionFactory.openSession(); // query string – ‘Address’ refers to a Class not a Table String queryString = " from Address " ; // create, configure and execute the query List addresses = session. createQuery ( queryString ). list ();

Hibernate Query Language HQL A more elaborate HQL Query –Return all Tracks in a Conference Conference conference = … session = sessionFactory.openSession(); // build a query string String queryString = “from Tracks as t where t.Conference = :conf”; // create, configure and execute the query List addresses = session.createQuery( queryString ).setObject(“conf”, conference ).list();

Hibernate Query Language HQL Parameters Named parameters removed positional problems May occur multiple times in the same query Self-documenting List tracks = new ArrayList(); tracks.add(“JSE"); tracks.add(“JEE"); Query q = session.createQuery("from Sessions s where s.Track in (:trackList)"); q.setParameterList(“ trackList ", tracks ); List sessions = q.list();

Hibernate Query Language HQL Parameters Specify bounds upon your result set The maximum number of rows The first row you want to retrieve Query query = session.createQuery("from Users"); query.setFirstResult(50); query.setMaxResults(100); List someUsers = query.list();

Query by Criteria Same query using the Criteria API –Return all Tracks for a given Conference Conference conference = … session = sessionFactory.openSession(); // create and expression to match the given conference Expression exp = Expression.eq(“Conference", conference ); List addresses = session.createCriteria( Tracks.class).add( exp ).list();

Query by Example Return all Address for a given Street Name Address address = new Address(); Address.setStreetAddress(“Main Street”); // create example object Example example = Example.create( address ).ignoreCase().enableLike(MatchMode.ANYWHERE); // create, configure and execute the query List matches = session.createCriteria( Address.class).add( example ).list();

Caching in Hibernate 1 st Level –Transaction scoped cache provided by the Session. –Always available 2 nd Level –Process scoped cache –Shared by all Sessions –Optional –Pluggable implementation, can be clustered Query –Use with care, profile first

Caching in Hibernate

Caching setting in HBM for Read Only <class name=“ReferenceData” table=“REFDATA”>..

Caching in Hibernate Caching setting in HBM for Read/Write Profile the application before applying <class name=“ReadMostly” table=“READMOSTLY”>..

Caching in Hibernate Query Caching, most difficult to get right Analyze/Profile First. Let usage determine which queries to cache String queryString = “from...”; List hits = session.createQuery( queryString ).setObject(“user”, user).setCacheable(true).list();

Other Hibernate Features Multiple Strategies for supporting Inheritance Scalar Query Results Projections Custom SQL for Loading, Updating and Deleting J2EE/JTA Friendly Spring Integration

Conclusions Why should you use Hibernate? It’s a well designed product. Look at the source! It covers 80% of your persistence needs and does a fine job on the other 20% You get to work with POJOs, not coarse- grained EJBs Performance is good! Boils down to the generated SQL –If you don’t like it, you can always use custom SQL

Conclusions Why should you use Hibernate? Good separation of integration tier and the rest of the application Avoid reinventing the well Good community support, large pool of talent

Let’s Look at some Code Quick Live Demos Some CRUD Demos Inheritance Demo –using Table-Per-Class-Hierarchy Hibernate Components Hibernate code in a J2EE app

Questions?

Thank you! You can contact me with questions at Our website Updated Slides Online

Shameless Plug ;-) get the book…

Shameless Plug ;-) …so that I can feed him