Hibernate Tutorial

6,657 views

Published on

Published in: Education, Technology
1 Comment
3 Likes
Statistics
Notes
No Downloads
Views
Total views
6,657
On SlideShare
0
From Embeds
0
Number of Embeds
1,124
Actions
Shares
0
Downloads
0
Comments
1
Likes
3
Embeds 0
No embeds

No notes for slide

Hibernate Tutorial

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

×