Orielly Hibernate Intro

Embed Size (px)

Citation preview

  • 8/8/2019 Orielly Hibernate Intro

    1/54

    Object-Relational Mapping with

    HibernateBrian Sam-Bodden

    Principal PartnerIntegrallis Software, LLC.

    August 1 - 5, 2005

  • 8/8/2019 Orielly Hibernate Intro

    2/54

    Contents The Problem

    Object-Relational Mapping

    Hibernate Core Concepts

    Hibernate Architecture

    Hibernate Mappings

    Configuring Hibernate

    Working with Persistent Objects Persistence Lifecycle

  • 8/8/2019 Orielly Hibernate Intro

    3/54

    Contents

    Working with Collections

    More on Association Mappings

    HQL The Hibernate Query Language

    Query by Criteria

    Query by Example

    Caching

    OtherHibernate Features

    Conclusions

  • 8/8/2019 Orielly Hibernate Intro

    4/54

    The Problem

    Two Different WorldsObject-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

  • 8/8/2019 Orielly Hibernate Intro

    5/54

    Early on in a systems life, both modelstend to look alike

    As the system matures two modelsdiverge

    They grow to do what they do best

    Object model gets richer

    Data model changes toaccommodate operational factors

    The Problem

    Natural Divergence

  • 8/8/2019 Orielly Hibernate Intro

    6/54

    The Problem

    Object-Relational Mismatch

    Granularity

    Object Oriented vs. Database Types

    User-Defined Column Types (UDT) arenot portable

    Inheritance & Polymorphism

    Not supported in the relational

    modelNo polymorphic queries

    Columns are strictly typed

  • 8/8/2019 Orielly Hibernate Intro

    7/54

    The Problem

    Object-Relational Mismatch

    Identity Mismatch

    Object Identity vs. Object Equality

    Different objects can map to thesame column or columns

    Database Identity Strategies

    Natural Keys versus Surrogate Keys

  • 8/8/2019 Orielly Hibernate Intro

    8/54

    The Problem

    Object-Relational Mismatch

    Associations

    Object References versus Foreign

    KeysDirectionality of Associations

    Tables associations are always one-to-many or many-to-one

    Object associations can be many-to-many

  • 8/8/2019 Orielly Hibernate Intro

    9/54

    The Problem

    Object-Relational Mismatch

    Object Graph Navigation

    Object-oriented applications walk

    the object graphObject-oriented systems access what

    they need

    With database we need a plan of

    what to retrieveN+1 Problem is a common symptom

  • 8/8/2019 Orielly Hibernate Intro

    10/54

    Object-Relational Mapping

    Tools/techniques to store and retrieveobjects 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

  • 8/8/2019 Orielly Hibernate Intro

    11/54

    HibernateRelational 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 theJBoss Group

  • 8/8/2019 Orielly Hibernate Intro

    12/54

    HibernateRelational Persistence For Idiomatic Java

    Declarative programming

    Uses Runtime Reflection

    Query Language is SQL-likeLeverages programmers knowledge

    Mappings

    Typically defined as XML documents But you neverhave to write XML if you

    dont want to (XDoclet, JSE 1.5 Annots)

  • 8/8/2019 Orielly Hibernate Intro

    13/54

    HibernateRelational Persistence For Idiomatic Java

  • 8/8/2019 Orielly Hibernate Intro

    14/54

    HibernateCore 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 ObjectsWraps a JDBC Connection / J2EE Data Source

    Serves as a first level object cache

  • 8/8/2019 Orielly Hibernate Intro

    15/54

    Architecture

  • 8/8/2019 Orielly Hibernate Intro

    16/54

    ArchitectureChoices

    How much you use depends on your needs

    Lightweight

    Basic persistenceFully Integrated

    Transactions

    CachingConnection Pooling

  • 8/8/2019 Orielly Hibernate Intro

    17/54

    O/R Mappings

    Hibernate Mapping (.hbm.xml) Files define:

    Column to Field Mappings

    Primary Key mapping & generation

    SchemeAssociations

    Collections

    Caching Settings

    Custom SQL

    And many more settings

  • 8/8/2019 Orielly Hibernate Intro

    18/54

    HBM XML File

  • 8/8/2019 Orielly Hibernate Intro

    19/54

    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, AnnotationsFrom Database Schema

    Middlegen, Synchronizer, Hibernate Tools

  • 8/8/2019 Orielly Hibernate Intro

    20/54

    Configuring Hibernate

    Hibernate Session Factory configured viahibernate.cfg.xml

    CFG file determines which mappings to load

    (.hbm.xml files)

    In your application SessionFactory is asingleton

    You request a Session as needed to workwith persistent objects

  • 8/8/2019 Orielly Hibernate Intro

    21/54

    The Big Picture

  • 8/8/2019 Orielly Hibernate Intro

    22/54

    Working with Persistent ObjectsSaving an Object

    Address address =newAddress();

    ...

    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 iscommitted

    The session is closed

  • 8/8/2019 Orielly Hibernate Intro

    23/54

    Working with Persistent ObjectsLoading 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

  • 8/8/2019 Orielly Hibernate Intro

    24/54

    Working with Persistent ObjectsDeleting 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

  • 8/8/2019 Orielly Hibernate Intro

    25/54

    Persistence LifecyclePossible States

    TransientNot Associated with a database tableNon-transactional

    PersistedObject with Database IdentityAssociates object with a SessionTransactional

    Detachedno longer guaranteed to be in synch with

    the database

  • 8/8/2019 Orielly Hibernate Intro

    26/54

    Persistence Lifecycle

  • 8/8/2019 Orielly Hibernate Intro

    27/54

    Working with Collections

    Can represent a parent-child/one-manyrelationship using most of the available JavaCollections

    Persistence by reach-ability No added semantics to your collections

    Available Collection mappings are ,,,, and In the database mappings are defined by aforeign key to the owning/parent entity

  • 8/8/2019 Orielly Hibernate Intro

    28/54

    Working with CollectionsAsimple example

  • 8/8/2019 Orielly Hibernate Intro

    29/54

    Working with CollectionsAsimple 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);

    }

  • 8/8/2019 Orielly Hibernate Intro

    30/54

    Working with CollectionsAsimple example

  • 8/8/2019 Orielly Hibernate Intro

    31/54

    Association MappingsSupported 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

  • 8/8/2019 Orielly Hibernate Intro

    32/54

    Association MappingsSome Details

    Inverse attribute used for bi-directionalassociations

    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

  • 8/8/2019 Orielly Hibernate Intro

    33/54

    Hibernate Query LanguageHQL

    An objectified version of SQL

    PolymorphicQueries

    Object parameters in Queries

    Less verbose than SQL

    Doesnt hide the power of SQL

    SQL joins, Cartesian products

    Projections

    Aggregation (max, avg) and grouping

    Ordering Sub-queries

    and more

  • 8/8/2019 Orielly Hibernate Intro

    34/54

    Hibernate Query LanguageHQL

    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();

  • 8/8/2019 Orielly Hibernate Intro

    35/54

    Hibernate Query LanguageHQL

    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();

  • 8/8/2019 Orielly Hibernate Intro

    36/54

    Hibernate Query LanguageHQL 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();

  • 8/8/2019 Orielly Hibernate Intro

    37/54

    Hibernate Query LanguageHQL 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();

  • 8/8/2019 Orielly Hibernate Intro

    38/54

    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();

  • 8/8/2019 Orielly Hibernate Intro

    39/54

    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();

  • 8/8/2019 Orielly Hibernate Intro

    40/54

  • 8/8/2019 Orielly Hibernate Intro

    41/54

    Caching in Hibernate

  • 8/8/2019 Orielly Hibernate Intro

    42/54

    Caching in Hibernate

    Caching setting in HBM for Read Only

    ..

  • 8/8/2019 Orielly Hibernate Intro

    43/54

    Caching in Hibernate

    Caching setting in HBM for Read/Write

    Profile the application before applying

    ..

  • 8/8/2019 Orielly Hibernate Intro

    44/54

    Caching in Hibernate

    Query Caching, most difficult to get right

    Analyze/Profile First. Let usage determinewhich queries to cache

    String queryString =from ...;

    List hits =session

    .createQuery(queryString)

    .setObject(user, user)

    .setCacheable(true)

    .list();

  • 8/8/2019 Orielly Hibernate Intro

    45/54

    Other Hibernate Features

    Multiple Strategies for supportingInheritance

    ScalarQuery Results

    ProjectionsCustom SQL for Loading, Updating

    and Deleting

    J2EE/JTA Friendly Spring Integration

  • 8/8/2019 Orielly Hibernate Intro

    46/54

    ConclusionsWhy should you use Hibernate?

    Its a well designed product. Look at thesource!

    It covers 80% of your persistence needs and

    does a fine job on the other20% You get to work with POJOs, not coarse-

    grained EJBs

    Performance is good! Boils down to the

    generated SQL If you dont like it, you can always use custom

    SQL

  • 8/8/2019 Orielly Hibernate Intro

    47/54

    ConclusionsWhy should you use Hibernate?

    Good separation of integration tier and therest of the application

    Avoid reinventing the well

    Good community support, large pool oftalent

  • 8/8/2019 Orielly Hibernate Intro

    48/54

    Lets Look at some CodeQuick Live Demos

    Some CRUD Demos

    Inheritance Demousing Table-Per-Class-Hierarchy

    Hibernate Components

    Hibernate code in a J2EE app

  • 8/8/2019 Orielly Hibernate Intro

    49/54

    Questions?

  • 8/8/2019 Orielly Hibernate Intro

    50/54

    Thank you!

    You can contact me with questions [email protected]

    Our website

    http://www.integrallis.com

    Updated SlidesOnline

  • 8/8/2019 Orielly Hibernate Intro

    51/54

    Shameless Plug ;-)get the book

  • 8/8/2019 Orielly Hibernate Intro

    52/54

    Shameless Plug ;-)so that I can feed him

  • 8/8/2019 Orielly Hibernate Intro

    53/54

  • 8/8/2019 Orielly Hibernate Intro

    54/54