KEMBAR78
Hibernate Tutorial | PPT
Introduction To Hibernate Presented by  Ryan Bohn and John Stein Versatile, Inc.
Agenda The problem with programming to relational databases The problem with EJB2 persistence What is Hibernate and how does it solve these problems? Where to get Hibernate Hibernate ORM Ways To Map: XML Mappings Annotations Types of mappings: basic - one-to-many / many-to-one / many-to-many/ one-to-one
Agenda (continued) Hibernate basics The Session Operations: load, save, delete Hibernate queries HQL Criteria queries Query by example Native queries Hibernate and Transactions Lazy loading Alternatives to Hibernate Q & A
Problem Programming to Relational DBs
Work with  large amounts  of data Searching, sorting Work with  sets  of data Joining, aggregating Sharing Concurrency (Transactions) Many applications Integrity Constraints Transaction isolation What do relational DBs do well?
Modeling No polymorphism / inheritance No support for automatic conversion to objects Business logic There’s stored procedures, but: Very database specific Very coupled with the data, really belongs in the application domain Transaction No concept of application level transactions What do relational DBs do badly?
Problem with EJB
EJB the answer? EJB spec tried to bridge the gap between programming and interacting with relational dbs EJB provides: Basic persistence (CMP) Method-level transaction management Automatic management of associations EJBQL provides a very basic object query language
Problems with EJB Noisy Programming model Inheritance from javax.ejb Interface / Implementation required but do we really need interfaces of our entity beans Complex deployment descriptors Weird combo of checked / unchecked exceptions No Polymorphism Can’t Test Outside Container For example, in JUnit Why not? Home is an interface Relationships/instantiation done by container
Problems with EJB (continued) EJBQL too limited – none of: Aggregation/projection for reporting Outer-join fetching Pagination Dynamic queries
The Hibernate Solution
The Hibernate Solution Hibernate is a persistence framework aimed at solving the shortcomings presented by EJB2. Persistence classes (entities) are POJOs Easy to write and refactor Can be serialized Can execute outside of the container (JUnit) Eg. public class Book { private Author author; public Author getAuthor()… public void setAuthor(…. }
The Hibernate Solution (cont.) POJO programming model Persistent properties are not abstract Can instantiate POJOS using new() Detached from persistence layer No Home Interface Generic Session interface is provided for persistence operations May write own DAO No method-level transactions for entities Rather emphasize transactions at the business level
The Hibernate Solution (cont.) Truly object-oriented Polymorphic associations and queries Three inheritance mapping strategies
Where to get Hibernate http://www.hibernate.org Download Jar Source code Javadoc Reference documentation Support forums Requirements JDK 1.4 or later Ehcache, commons logging, commons collections, asm, dom4j, antlr, cglib
Hibernate ORM
Hibernate ORM ORM = Object Relational Mapping: way of telling the container (Hibernate) how to map tables and columns to entity beans Eg. public class AuctionItem { private Long id; private String description; private Set bids; } varchar(100) DESC int8 ITEM_ID AUCTION_ITEM int8 ITEM_ID int4 AMT int8 BID_ID BID
Hibernate ORM with XML Hibernate supports mappings via XML: <class name=“AuctionItem” table=“AUCTION_ITEM”> <id name=“id” column=“ITEM_ID”> <generator class=“native”/> </id> <property name=“description” column=“DESCR”/> <set name=“bids”  cascade=“all” lazy=“true”> <key column=“ITEM_ID”/> <one-to-many class=“Bid”/> </set> </class> XML is yucky!
Hibernate ORM with EJB3 annotations Hibernate 3 supports ORM via annotations.  Advantages are: Compatible with EJB3 Keeps mapping with the entity No XML sit-ups Disadvantage: Java 5 required So what does AuctionItem look like in the annotated version
Hibernate ORM with Annotations @Entity @Table(name = “AUCTION_ITEM”) public class AuctionItem { private Long id; private String description; private Set<Bid> bids; @Id  @Column(name = “ITEM_ID”, nullable = false) public Long getId() {…} @Column(name = “DESC”, nullable = false) public String getDescription {…} @OneToMany(mappedBy = “item”) public Set<Bid> getBids {…} } Example
Available Annotations @Entity – tells Hibernate Persist Me! @Table – basic table info such as name @Id – Marks the getter as primary key, by default uses databases native id generator (auto-increment, sequences, etc.) @Column – generic information about the column (name, allows null, length, etc.) @OneToOne – maps a one-to-one relationship between 2 tables @OneToMany / @ManyToOne @ManyToMany – association table
Available Annotations @Inheritence Three strategies Table per class Table per class hierarchy Joined subclass Many more annotations!
Basic Persistence Operations
Basic Persistence Operations All persistence operations are done through  org.hibernate.Session  , which is retrieved through a SessionFactory Loading an object by its id long itemId = 500; Session session = sessionFactory.openSession(); AuctionItem item =  (AuctionItem) session.get(AuctionItem.class, itemId);
Basic Persistence Operations Creating a new row in the database AuctionItem item = new AuctionItem(); item.setDescription(“Antique Chair”); session.save(item) Updating a row item.setDescription(“Old Chair”); session.update(item); // not always necessary For fun, let’s see equivalent operations in JDBC
JDBC get Connection conn =  DriverManager.getConnection(…) String sql = “SELECT * FROM auction”; stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while (rs.next) { Auction auction = new Auction(); auction.setName(rs.getString(“name”)); . . . } // we did not even cover getting  // the associated entities!!! example
Querying objects in Hibernate
Hibernate Querying Hibernate several ways to query for objects HQL – Hibernate Query Language Criteria Queries Query by Example Native SQL Queries
Hibernate Query Language Make SQL be object oriented Classes and properties instead of tables and columns Polymorphism Associations Much  less verbose than SQL Full support for relational operations Inner/outer/full joins, cartesian products Projection Aggregation (max, avg) and grouping Ordering Subqueries SQL function calls
Hibernate Query Language Simplest HQL Query: from AuctionItem i.e.  get all the AuctionItems: List allAuctions = session.createQuery(“from AuctionItem”) .list();
Hibernate Query Language More realistic example: select item from AuctionItem item join item.bids bid where item.description like :desc and bid.amount > 100 :desc is a named parameter
Hibernate Query Language Projection: select item.description, bid.amount from AuctionItem item join item.bids bid where bid.amount > 100 order by bid.amount desc
Hibernate Query Language Aggregation: select max(bid.amount), count(bid) from AuctionItem item left join item.bids bid group by item.type order by max(bid.amount)
Criteria Queries Criteria queries provide: - way of generating queries through method calls - suited well for dynamic queries - extensible
Criteria Queries List auctionItems =  session.createCriteria(AuctionItem.class) .setFetchMode(“bids”, FetchMode.EAGER) .add( Expression.like(“description”, description) ) .createCriteria(“successfulBid”) .add( Expression.gt(“amount”, minAmount) ) .list(); Equivalent HQL: from AuctionItem item left join fetch item.bids where item.description like :description and item.successfulbid.amount > :minAmount
Hibernate Querying Query By Example: AuctionItem item = new AuctionItem(); item.setDescription(“hib”); Bid bid = new Bid(); bid.setAmount(1.0); List auctionItems =  session.createCriteria(AuctionItem.class) .add( Example.create(item).enableLike(MatchMode.START) ) .createCriteria(“bids”) .add( Example.create(bid) ) .list(); EXAMPLE
Transactions in Hibernate
Hibernate Transactions Like other operations, transactions are performed using the Session object.  Here’s an example: Session session = sf.openSession(); Transaction tx = session.beginTransaction(); try { AuctionItem item =  (AuctionItem) session.get(ActionItem.class, itemId); bid.setItem(item); item.getBids().add(bid); tx.commit(); } catch (Exception e) { tx.rollback(); throw e; } finally { session.close(); }
Hibernate Transactions Some advice -  Wrap all write operations in a transaction.  Otherwise, calling a setter could automatically go back to the database
Lazy Loading
Lazy Loading By default all one-to-many associations don’t get fetched immediately.  For example, load an AuctionItem, but it doesn’t load bids until the first call Accomplished with dynamic proxies using CGLIB Can change by setting fetchmode on a column mapping Be wary of this if passing object to view after session has been closed
Alternatives to Hibernate
Alternatives to Hibernate Oracle Toplink Ibatis JDO Many more EJB3 – not really, most likely Hibernate will be an implementation of EJB3 persistence JBOSS does this today!
Q & A

Hibernate Tutorial

  • 1.
    Introduction To HibernatePresented by Ryan Bohn and John Stein Versatile, Inc.
  • 2.
    Agenda The problemwith programming to relational databases The problem with EJB2 persistence What is Hibernate and how does it solve these problems? Where to get Hibernate Hibernate ORM Ways To Map: XML Mappings Annotations Types of mappings: basic - one-to-many / many-to-one / many-to-many/ one-to-one
  • 3.
    Agenda (continued) Hibernatebasics The Session Operations: load, save, delete Hibernate queries HQL Criteria queries Query by example Native queries Hibernate and Transactions Lazy loading Alternatives to Hibernate Q & A
  • 4.
    Problem Programming toRelational DBs
  • 5.
    Work with large amounts of data Searching, sorting Work with sets of data Joining, aggregating Sharing Concurrency (Transactions) Many applications Integrity Constraints Transaction isolation What do relational DBs do well?
  • 6.
    Modeling No polymorphism/ inheritance No support for automatic conversion to objects Business logic There’s stored procedures, but: Very database specific Very coupled with the data, really belongs in the application domain Transaction No concept of application level transactions What do relational DBs do badly?
  • 7.
  • 8.
    EJB the answer?EJB spec tried to bridge the gap between programming and interacting with relational dbs EJB provides: Basic persistence (CMP) Method-level transaction management Automatic management of associations EJBQL provides a very basic object query language
  • 9.
    Problems with EJBNoisy Programming model Inheritance from javax.ejb Interface / Implementation required but do we really need interfaces of our entity beans Complex deployment descriptors Weird combo of checked / unchecked exceptions No Polymorphism Can’t Test Outside Container For example, in JUnit Why not? Home is an interface Relationships/instantiation done by container
  • 10.
    Problems with EJB(continued) EJBQL too limited – none of: Aggregation/projection for reporting Outer-join fetching Pagination Dynamic queries
  • 11.
  • 12.
    The Hibernate SolutionHibernate is a persistence framework aimed at solving the shortcomings presented by EJB2. Persistence classes (entities) are POJOs Easy to write and refactor Can be serialized Can execute outside of the container (JUnit) Eg. public class Book { private Author author; public Author getAuthor()… public void setAuthor(…. }
  • 13.
    The Hibernate Solution(cont.) POJO programming model Persistent properties are not abstract Can instantiate POJOS using new() Detached from persistence layer No Home Interface Generic Session interface is provided for persistence operations May write own DAO No method-level transactions for entities Rather emphasize transactions at the business level
  • 14.
    The Hibernate Solution(cont.) Truly object-oriented Polymorphic associations and queries Three inheritance mapping strategies
  • 15.
    Where to getHibernate http://www.hibernate.org Download Jar Source code Javadoc Reference documentation Support forums Requirements JDK 1.4 or later Ehcache, commons logging, commons collections, asm, dom4j, antlr, cglib
  • 16.
  • 17.
    Hibernate ORM ORM= Object Relational Mapping: way of telling the container (Hibernate) how to map tables and columns to entity beans Eg. public class AuctionItem { private Long id; private String description; private Set bids; } varchar(100) DESC int8 ITEM_ID AUCTION_ITEM int8 ITEM_ID int4 AMT int8 BID_ID BID
  • 18.
    Hibernate ORM withXML Hibernate supports mappings via XML: <class name=“AuctionItem” table=“AUCTION_ITEM”> <id name=“id” column=“ITEM_ID”> <generator class=“native”/> </id> <property name=“description” column=“DESCR”/> <set name=“bids” cascade=“all” lazy=“true”> <key column=“ITEM_ID”/> <one-to-many class=“Bid”/> </set> </class> XML is yucky!
  • 19.
    Hibernate ORM withEJB3 annotations Hibernate 3 supports ORM via annotations. Advantages are: Compatible with EJB3 Keeps mapping with the entity No XML sit-ups Disadvantage: Java 5 required So what does AuctionItem look like in the annotated version
  • 20.
    Hibernate ORM withAnnotations @Entity @Table(name = “AUCTION_ITEM”) public class AuctionItem { private Long id; private String description; private Set<Bid> bids; @Id @Column(name = “ITEM_ID”, nullable = false) public Long getId() {…} @Column(name = “DESC”, nullable = false) public String getDescription {…} @OneToMany(mappedBy = “item”) public Set<Bid> getBids {…} } Example
  • 21.
    Available Annotations @Entity– tells Hibernate Persist Me! @Table – basic table info such as name @Id – Marks the getter as primary key, by default uses databases native id generator (auto-increment, sequences, etc.) @Column – generic information about the column (name, allows null, length, etc.) @OneToOne – maps a one-to-one relationship between 2 tables @OneToMany / @ManyToOne @ManyToMany – association table
  • 22.
    Available Annotations @InheritenceThree strategies Table per class Table per class hierarchy Joined subclass Many more annotations!
  • 23.
  • 24.
    Basic Persistence OperationsAll persistence operations are done through org.hibernate.Session , which is retrieved through a SessionFactory Loading an object by its id long itemId = 500; Session session = sessionFactory.openSession(); AuctionItem item = (AuctionItem) session.get(AuctionItem.class, itemId);
  • 25.
    Basic Persistence OperationsCreating a new row in the database AuctionItem item = new AuctionItem(); item.setDescription(“Antique Chair”); session.save(item) Updating a row item.setDescription(“Old Chair”); session.update(item); // not always necessary For fun, let’s see equivalent operations in JDBC
  • 26.
    JDBC get Connectionconn = DriverManager.getConnection(…) String sql = “SELECT * FROM auction”; stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while (rs.next) { Auction auction = new Auction(); auction.setName(rs.getString(“name”)); . . . } // we did not even cover getting // the associated entities!!! example
  • 27.
  • 28.
    Hibernate Querying Hibernateseveral ways to query for objects HQL – Hibernate Query Language Criteria Queries Query by Example Native SQL Queries
  • 29.
    Hibernate Query LanguageMake SQL be object oriented Classes and properties instead of tables and columns Polymorphism Associations Much less verbose than SQL Full support for relational operations Inner/outer/full joins, cartesian products Projection Aggregation (max, avg) and grouping Ordering Subqueries SQL function calls
  • 30.
    Hibernate Query LanguageSimplest HQL Query: from AuctionItem i.e. get all the AuctionItems: List allAuctions = session.createQuery(“from AuctionItem”) .list();
  • 31.
    Hibernate Query LanguageMore realistic example: select item from AuctionItem item join item.bids bid where item.description like :desc and bid.amount > 100 :desc is a named parameter
  • 32.
    Hibernate Query LanguageProjection: select item.description, bid.amount from AuctionItem item join item.bids bid where bid.amount > 100 order by bid.amount desc
  • 33.
    Hibernate Query LanguageAggregation: select max(bid.amount), count(bid) from AuctionItem item left join item.bids bid group by item.type order by max(bid.amount)
  • 34.
    Criteria Queries Criteriaqueries provide: - way of generating queries through method calls - suited well for dynamic queries - extensible
  • 35.
    Criteria Queries ListauctionItems = session.createCriteria(AuctionItem.class) .setFetchMode(“bids”, FetchMode.EAGER) .add( Expression.like(“description”, description) ) .createCriteria(“successfulBid”) .add( Expression.gt(“amount”, minAmount) ) .list(); Equivalent HQL: from AuctionItem item left join fetch item.bids where item.description like :description and item.successfulbid.amount > :minAmount
  • 36.
    Hibernate Querying QueryBy Example: AuctionItem item = new AuctionItem(); item.setDescription(“hib”); Bid bid = new Bid(); bid.setAmount(1.0); List auctionItems = session.createCriteria(AuctionItem.class) .add( Example.create(item).enableLike(MatchMode.START) ) .createCriteria(“bids”) .add( Example.create(bid) ) .list(); EXAMPLE
  • 37.
  • 38.
    Hibernate Transactions Likeother operations, transactions are performed using the Session object. Here’s an example: Session session = sf.openSession(); Transaction tx = session.beginTransaction(); try { AuctionItem item = (AuctionItem) session.get(ActionItem.class, itemId); bid.setItem(item); item.getBids().add(bid); tx.commit(); } catch (Exception e) { tx.rollback(); throw e; } finally { session.close(); }
  • 39.
    Hibernate Transactions Someadvice - Wrap all write operations in a transaction. Otherwise, calling a setter could automatically go back to the database
  • 40.
  • 41.
    Lazy Loading Bydefault all one-to-many associations don’t get fetched immediately. For example, load an AuctionItem, but it doesn’t load bids until the first call Accomplished with dynamic proxies using CGLIB Can change by setting fetchmode on a column mapping Be wary of this if passing object to view after session has been closed
  • 42.
  • 43.
    Alternatives to HibernateOracle Toplink Ibatis JDO Many more EJB3 – not really, most likely Hibernate will be an implementation of EJB3 persistence JBOSS does this today!
  • 44.