• Save
Hibernate Training
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

Hibernate Training

  • 13,492 views
Uploaded on

http://www.intertech.com/Courses/Course.aspx?CourseID=99267 ...

http://www.intertech.com/Courses/Course.aspx?CourseID=99267

This is a slide deck from an Intertech presentation on Hibernate delivered as an Oxygen Blast.

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
13,492
On Slideshare
13,245
From Embeds
247
Number of Embeds
23

Actions

Shares
Downloads
0
Comments
8
Likes
78

Embeds 247

http://www.techgig.com 114
http://www.slideshare.net 43
http://majorjai.blogspot.co.uk 20
http://192.168.1.2 17
http://majorjai.blogspot.in 12
http://192.168.6.52 10
http://majorjai.blogspot.com 5
http://bloggiselia.blogspot.com 5
http://static.slidesharecdn.com 4
http://www.linkedin.com 2
http://majorjai.blogspot.it 2
http://majorjai.blogspot.fr 2
http://192.168.1.6 1
http://allinfo.66ghz.com 1
http://www.pinterest.com 1
http://www.bloggiselia.blogspot.com.br 1
http://majorjai.blogspot.de 1
http://onlinelpnprogramsx.com 1
http://www.majorjai.blogspot.co.uk 1
http://www.majorjai.blogspot.in 1
http://www.health.medicbd.com 1
http://www.bloggiselia.blogspot.com 1
http://majorjai.blogspot.dk 1

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Oxygen Blast IV: Java Persistence with Hibernate “It ain’t about napping!” An Intertech Presentation Copyright © Intertech, Inc. 2006. All Rights Reserved.
  • 2. Oxygen Blast: Java Persistence with Hibernate Welcome and Thank you! Thank you for your time today. We hope you learn something about one of the most widely used persistence frameworks in Java! We hope you will think about coming back to take a class from us. Maybe our Complete Hibernate class? We have been training Minnesota developers since 1991. We started one of the first Java users groups in the US. We have a customer satisfaction rate of > 99.5%. Let us know if our consultants can help in your project. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 2
  • 3. Oxygen Blast: Java Persistence with Hibernate About Me My email address is jwhite@intertech.com. Director of training at Intertech as well as an instructor. Author J2ME, Java in Small Things – 2002, Manning International Speaker Including JavaOne Contributor to many journals including: JDJ DevX.com JavaPro Consultant, engineer and architect with several companies Most recently a Senior Technical Architect at Target Corp. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 3
  • 4. Oxygen Blast: Java Persistence with Hibernate About You With a show of hands, how many people… Have at least a year of Java development experience? Have coded in JDBC? How many of those liked it? Have tried other persistence frameworks? Like EJB CMP, Castor, iBatis, JDO, etc.? How many were pleased with the results from those? Have used Hibernate already? Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 4
  • 5. Oxygen Blast: Java Persistence with Hibernate Talk Objectives This talk is meant to provide even the Java novice with some appreciation of: What Hibernate is and When to consider using it. For the more advanced Java developer, hopefully this talk will: Highlight Hibernates power and Highlight Hibernates flexibility and Give you resource points for more information Give you some food for thought with regard to using Hibernate in your design. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 5
  • 6. Oxygen Blast: Java Persistence with Hibernate Talk Outline What is Hibernate? Why Hibernate? What are the alternatives to Hibernate? Object relational mapping issues Simple Hibernate example Hibernate architecture Hibernate power Advanced association mapping Advanced inheritance mapping Flexibility and extensibility Hibernate design consideration (tips and tricks) Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 6
  • 7. Oxygen Blast: Java Persistence with Hibernate What is Hibernate? Hibernate is an object-relational mapping framework. Established in 2001. In English, that means it provides tools to get Java objects in an out of the database. It also helps get their relationships to other objects in and out of the DB. It does so without a lot of intrusion. You don’t have to know a lot of Hibernate API. You don’t have to know or use a lot of SQL. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 7
  • 8. Oxygen Blast: Java Persistence with Hibernate Why use Hibernate? Too much developer time is spent getting data in and out of the database and objects (in this case Java objects). Take a guess! What percentage of development time is spent writing code to persist or manage access to relational data? A) Less than10% B) Around 20% C) Around 50% D) Around 70% E) Almost 90% Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 8
  • 9. Oxygen Blast: Java Persistence with Hibernate Estimates range between 30-70% That’s 30-70% of your developer time… Not spent on design. Not spent on writing business logic. Not testing the application. Not solving business problems! Don’t forget the maintenance and management of all that code too! Sources http://www.thoughtinc.com/cber_roi_whitepaper.html http://www.cognitivemachines.com/JDOchat.html http://www.thoughtinc.com/cut_cost.pdf http://www.intersystems.com/cache/technology/whitepapers /hybrid.html Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 9
  • 10. Oxygen Blast: Java Persistence with Hibernate More on Why Hibernate… Hibernate’s stated goal “is to relieve the developer from 95 percent of common data persistence related programming tasks.” Even using conservative numbers that 95% of 30% = > 25% increase in productivity! Hibernate can also help your application be more platform independent/portable. Database access configuration and SQL are all removed or at least moved to configuration files. Hibernate can help with performance! Hibernate generates efficient queries consistently. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 10
  • 11. Oxygen Blast: Java Persistence with Hibernate Alternatives Hibernate is certainly not the only object-relational mapping framework. There are dozens of commercial and open source options. Java Persistence API – still a very young and evolving API by Sun (from the same group providing EJB 3). Finding implementations still an issue. Java Data Objects (JDO) – Guided by JSR-12 specification but requires additional “compilation” step that alters the .class files. EJB Container Managed Persistence (CMP) – Guided by specifications (pick one). Pretty complex technology and easy to get it “wrong.” iBatis – Flexible open source product but requires a lot of SQL skills. TopLink – commercial product now owned by Oracle. Castor – Open source ORM but not as popular or as fast as Hibernate. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 11
  • 12. Oxygen Blast: Java Persistence with Hibernate Why so many ORMs? Mapping objects to relational data is hard! The two systems satisfy different needs. Structured data storage/retrieval/sorting vs. entity that represents the state and functions of a real world thing. There are a number of obstacles to overcome based in the differences. Identity Granularity Associations Navigation Inheritance Data type mismatches An ORM framework must overcome these well to be successful. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 12
  • 13. Oxygen Blast: Java Persistence with Hibernate Identity A row is uniquely identified from all other rows by its primary key. An object’s identity doesn’t always translate well to the concept of primary key. In Java, what is an object’s identity? Its data or its place in memory? Consider the following: are two objects equal or “identical”? accountA.equals(accountB); accountA==accountB Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 13
  • 14. Oxygen Blast: Java Persistence with Hibernate Granularity Objects and tables are often modeled with different levels of granularity. Table structures are often “de-normalized” in order support better performance. Table rows end up mapping to multiple objects. Objects tend to be more fine grained. first last ssn city street state zip username password Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 14
  • 15. Oxygen Blast: Java Persistence with Hibernate Associations Associations in Java are either unidirectional or bidirectional. Based on what attributes and accessors (getters/setters are available in the object. Cardinality is represented only by more complex objects (lists, sets, etc). Object identification can impact certain associations (Sets). Relating data in database tables is based on joins. There is no concept of directionality. Items are related or not. Many to many relationships require the addition of a join table. Identity, especially foreign key identity, greatly impacts associations. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 15
  • 16. Oxygen Blast: Java Persistence with Hibernate Association Example Java objects Options to consider Does address know the customer? Does the customer have >1 address? Can an address be owned by >1 customer? Data tables Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 16
  • 17. Oxygen Blast: Java Persistence with Hibernate Navigation and Association Traversal Navigating Java objects to get property information often requires traversal of the object graph. This can be quite expensive if the objects are distributed or need to be created before traversed. Consider getting the address to ship an order in this example. anAcct = anOrder.getAccount(); aCust = anAcct.getCustomer(); orderAddress = aCust.getAddress(); shipTo(orderAddress); Navigation in databases is handled, potentially, by a single join. select a.street, a.city, a.state, a.zip from address a, order o, account t, customer c where o.id = t.order_id and t.customer_id=c.id and c.address_id = a.id Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 17
  • 18. Oxygen Blast: Java Persistence with Hibernate Inheritance Inheritance and polymorphism are important concepts in OO programming languages like Java. Add power and flexibility to our programming environments. Databases have no equivalent concept to inheritance. Mapping inheritance trees in Java to the database creates an opportunity for creativeness. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 18
  • 19. Oxygen Blast: Java Persistence with Hibernate Inheritance Example Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 19
  • 20. Oxygen Blast: Java Persistence with Hibernate Datatypes Even simple types are not easily mapped between Java and the major relational databases. For that matter, simple data types are not easily mapped among the various vendor relational database! Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 20
  • 21. Oxygen Blast: Java Persistence with Hibernate Datatypes Example Some Java Data Types vs. SQL Data Types Java Data Type SQL Data Type String VARCHAR String CHARACTER String LONGVARCHAR BigDecimal NUMERIC BigDecimal DECIMAL Boolean, boolean BIT Integer, byte TINYINT Integer, short SMALLINT Integer, long BIGINT Integer, int INTEGER Float, float REAL Double, double FLOAT Double, double DOUBLE PRECISION Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 21
  • 22. Oxygen Blast: Java Persistence with Hibernate Hibernate To The Rescue Hibernate handles all of these issues. In fact, Hibernate provides several options in most cases to allow you to handle them in a variety of ways. Why the options? The database may have come before the application (lay on top of legacy systems). The application may drive the development of the database (green field applications). The database and application must be integrated (meet-in-the-middle approach). Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 22
  • 23. Oxygen Blast: Java Persistence with Hibernate A Simple Example of Hibernate So what does Hibernate code package com.intertech.hibernate.Customer; import java.util.Date; look like? public class Customer { Let’s examine a simple private long id; private String name; application. private char gender; // m = male; f = female; private Date dateOfBirth; To demonstrate the simplicity public Date getDateOfBirth() { and unobtrusive behavior of } return dateOfBirth; Hibernate. public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; Let’s start with a customer class } like that to the right. public char getGender() { return gender; } public void setGender(char gender) { this.gender = gender; } public long getId() { return id; } private void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 23 }
  • 24. Oxygen Blast: Java Persistence with Hibernate Creating and Saving Code to create a couple of //package and imports removed for brevity customers and save them to the public class MakeCustomers { DB. public static void main(String[] args) { How much SQL do you see? Customer tom = new Customer(); How much connection, tom.setName(quot;Tom Salonekquot;); tom.setGender('M'); statement, code do you see? tom.setDateOfBirth(new Date()); In fact, the SessionFactory line Customer dan = new Customer(); is usually done elsewhere. dan.setName(quot;Dan McCabequot;); dan.setGender('M'); dan.setDateOfBirth(new Date()); SessionFactory sf = new Configuration(). configure().buildSessionFactory(); Session session = sf.openSession(); Transaction trx = session.beginTransaction(); session.save(tom); session.save(dan); trx.commit(); session.close(); sf.close(); } } Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 24
  • 25. Oxygen Blast: Java Persistence with Hibernate Retrieving Code to fetch and iterate //package and imports removed for brevity through all the customers. import org.hibernate.*; Again, how much SQL do you import org.hibernate.cfg.Configuration; import java.util.*; see? How much connection, public class ReadCustomers { statement, code do you see? public static void main (String[] args){ SessionFactory sf = new Configuration(). configure().buildSessionFactory(); Session session = sf.openSession(); Query q = session.createQuery(quot;from Customerquot;); List customers = q.list(); for (Iterator i=customers.iterator(); i.hasNext(); ) { Customer cust = (Customer)i.next(); System.out.println(cust.getName() + quot; says hello.quot;); } session.close(); } } Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 25
  • 26. Oxygen Blast: Java Persistence with Hibernate Updating Code to get and update a //package and imports removed for brevity single customer. public class MakeUpdate { SQL code? JDBC code? public static void main(String[] args) { SessionFactory sf = new Configuration(). configure().buildSessionFactory(); Session session = sf.openSession(); Transaction trx = session.beginTransaction(); Customer tom = (Customer)session. get(com.intertech.Customer.class, new Long(1)); tom.setGender('F'); trx.commit(); session.close(); sf.close(); } } Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 26
  • 27. Oxygen Blast: Java Persistence with Hibernate Configuring Hibernate In order to get the previous examples to work, two types of configuration files must also be provided. A hibernate.cfg.xml file defines all the database connection information. This can be done in a standard properties file (key-value pairs) or in the preferred XML format. The configuration supports both managed (app server with a data source) or non-managed environments. Allowing for easy to setup and use dev, test, prod environments. A classname.hbm.xml maps class properties to the database table/columns. Traditionally one configuration per class. Stored with the .class file. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 27
  • 28. Oxygen Blast: Java Persistence with Hibernate Configuration Files Customer.hbm.xml hibernate.cfg.xml <?xml version=quot;1.0quot;?> <?xml version=quot;1.0quot; encoding=quot;utf-8quot;?> <!DOCTYPE hibernate-mapping <!DOCTYPE hibernate-configuration PUBLIC quot;-//Hibernate/Hibernate Configuration DTD//ENquot; PUBLIC quot;-//Hibernate/Hibernate Mapping quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtdquot;> DTD//ENquot; <hibernate-configuration> quot;http://hibernate.sourceforge.net/hibernate- <session-factory> mapping-3.0.dtdquot;> <property name=quot;dialectquot;> org.hibernate.dialect.MySQLDialect <hibernate-mapping> </property> <class <property name=quot;connection.urlquot;> name=quot;com.intertech.hibernate.Customer“ jdbc:mysql://localhost:3306/hibernateexamples table=quot;customerquot;> </property> <id name=quot;idquot; column=quot;idquot; <property name=quot;connection.usernamequot;>root</property> type=quot;java.lang.Longquot;> <property name=quot;connection.passwordquot;>root</property> <generator class=quot;incrementquot;/> <property name=quot;connection.driver_classquot;> com.mysql.jdbc.Driver </id> </property> <property name=quot;namequot; not-null=quot;truequot;/> <mapping <property name=quot;genderquot;/> resource=quot;com/intertech/hibernate/example/Customer.hbm.xmlquot; /> <property name=quot;dateOfBirthquot; column=quot;dobquot; </session-factory> </hibernate-configuration> type=quot;datequot;/> </class> </hibernate-mapping> Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 28
  • 29. Oxygen Blast: Java Persistence with Hibernate Hibernate Architecture and API Again, the point of Hibernate is to be non-intrusive with regard to your application. Removing SQL and JDBC-like calls from business code as much as possible. The Hibernate architecture is actually quite simple. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 29
  • 30. Oxygen Blast: Java Persistence with Hibernate Configuration As seen in the example code, a Configuration object is the first Hibernate object you use. The Configuration object is usually created once during application initialization. The Configuration object reads and establishes the properties Hibernate uses to get connected. By default, the Configuration loads configuration property information and mapping files from the classpath. The Configuration object can be told explicitly where to find files. The Configuration object is used to create a SessionFactory and then typically discarded. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 30
  • 31. Oxygen Blast: Java Persistence with Hibernate SessionFactory The SessionFactory is created from a Configuration object. SessionFactory sf = cfg.buildSessionFactory(); The SessionFactory is an expensive object to create. It too is usually created during application start up. It should be created once and kept for later use. The SessionFactory object is used by all the threads of an application. It is a thread safe object. One SessionFactory object is created per database (where connecting to multiple databases). The SessionFactory is used to create Session objects. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 31
  • 32. Oxygen Blast: Java Persistence with Hibernate Session The Session object is created from the SessionFactory object. Session session = sf.openSession(); A Session object is lightweight and inexpensive to create. Session objects provide the main interface to accomplish work with the database. Does the work of getting a physical connection to the database (hopefully from a connection pool). Session objects are not thread safe. Session objects should not be kept open for a long time. Applications create and destroy these as needed. Typically, they are created to complete a single unit of work. When modifications are made to the database, session objects are used to create a transaction object. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 32
  • 33. Oxygen Blast: Java Persistence with Hibernate Transaction Transaction objects are obtained from the session object when a modification to the database is needed. Transaction trx = session.beginTransaction(); The Transaction object provides abstraction for the underlying implementation. Hibernate with use whatever transaction implementation is available (JDBC, JTA, etc.). It is optional; allowing developers to use their own transactional infrastructure. Transaction objects should be kept open for as short of time as possible. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 33
  • 34. Oxygen Blast: Java Persistence with Hibernate That’s the API Basics! Configuration, SessionFactory, Session and Transaction (along with your own persistent classes) gets you started. In fact, most of Hibernate “coding” is spent in the two configuration files. hibernate.cfg.xml or hibernate.properties Classname.hbm.xml (one per persistent class) The toughest part of Hibernate is getting your persistent mapping file set up. Understanding and picking the best option for properties. Understanding and picking the best option for associations. Understanding and picking the best option for your inheritance tree. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 34
  • 35. Oxygen Blast: Java Persistence with Hibernate Object Lifecycle Persistent object (like the tom customer object) are synchronized with the database. That is, the object’s state and the affected database rows are kept the same whenever either chages. Domain objects are in one of three states. Transient Persistent Detached An object’s state determine if it is kept synchronized with the database. The presence of a session and certain method calls move an object between states. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 35
  • 36. Oxygen Blast: Java Persistence with Hibernate Object State Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 36
  • 37. Oxygen Blast: Java Persistence with Hibernate Persistent to Detached We’ve already seen an example of moving from a new transient object to a persistent object state. Here is an example of an object in detached state. Customer dave = new Customer(); Session session = sf.openSession(); Transaction t = session.beginTransaction(); session.save(dave); t.commit(); session.close(); //dave is now detached since the session is gone dave.setGender(‘M’); //data not synch’ed in DB Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 37
  • 38. Oxygen Blast: Java Persistence with Hibernate Detached to Persistent //customer dave was created in another session... //that session was then closesd. dave.setDateOfBirth(new Date()); Session session = sf.openSession(); Transaction t = session.beginTransaction(); session.update(dave); //reattaches an object //in persistent state & synchs data dave.setGender(‘F’); t.commit(); session.close(); Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 38
  • 39. Oxygen Blast: Java Persistence with Hibernate Back to Transient Session session = sf.openSession(); Transaction t = session.beginTransaction(); Long id = new Long(1); Customer tom = session.get(Customer.class, id); session.delete(tom); t.commit(); session.close(); //tom row is gone in the database //tom is still a valid object reference at this point, but it is no longer persistent. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 39
  • 40. Oxygen Blast: Java Persistence with Hibernate Associations Hibernate provides a rich set of alternatives for mapping object associations in the database. Providing for all the various multiplicities of relationships. Many to one One to many Many to many One to one Providing for Java’s understanding of directionality. Unidirectional Bidirectional Providing for fine grained control of “transitive persistence” tran what…??? ?? Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 40
  • 41. Oxygen Blast: Java Persistence with Hibernate Transitive Persistence Controls when/how associated objects react to changes in the other. For example, should associated address rows be deleted when a customer object is removed (cascade delete). When an new order is saved should associated new line item objects also be saved (cascade save). Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 41
  • 42. Oxygen Blast: Java Persistence with Hibernate Association Mapping Association mapping is public class Order { primarily handled in the class private Set items; // association mapping files. public Set getOrderItems() { The class must provide the return items; standard property and } getter/setter methods. private void setOrderItems(Set i) { For example, an Order that has items=i; an association to a set of Order } Items would need definitions } similar to those at right. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 42
  • 43. Oxygen Blast: Java Persistence with Hibernate Example one-to-many mapping In Order.hbm.xml <class name=“Order”> <id name=“id” column=“ORDER_ID”> <generator class=“native”/> </id> <set name=“orderItems” inverse=“true”> <key column=“ORDER_ID”/> <one-to-many class=“OrderItem”/> </set> </class> Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 43
  • 44. Oxygen Blast: Java Persistence with Hibernate Bidirectional To make the association bidirection, OrderItem would also need appropriate getters/setters and this mapping. <class name=“OrderItem”> <id name=“id” column=“ORDER_ITEM_ID”> <generator class=“native”/> </id> <many-to-one name=“order” column=“ORDER_ID” class=“Order”/> </class> Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 44
  • 45. Oxygen Blast: Java Persistence with Hibernate Other types of Associations Hibernate provides for the other types of multiplicity. One to one Many to many It also supports some unique mappings. Component mapping (Customer/Address where both objects are in the same row in the DB). Collection of components. Collection of “value types” like date objects, Strings, etc. Polymorphic associations (association to a payment might actually be a check payment or a credit card payment object). Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 45
  • 46. Oxygen Blast: Java Persistence with Hibernate Inheritance Hibernate also handles inheritance associations. In fact, it supports three strategies with regard to inheritance mapping. Table per concrete class Table per subclass Table per class hierarchy Let’s look at an example inheritance tree and examine the options. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 46
  • 47. Oxygen Blast: Java Persistence with Hibernate Table per Concrete Class Savings_Accounts Checking_Accounts Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 47
  • 48. Oxygen Blast: Java Persistence with Hibernate Table per Subclass Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 48
  • 49. Oxygen Blast: Java Persistence with Hibernate Table per Class Hierarchy Discriminator of type 1 Discriminator of type 2 Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 49
  • 50. Oxygen Blast: Java Persistence with Hibernate Inheritance in the Mapping Example of Hierarchy mapping <class name=“BankAccount”> <id name=“accountNum” column=“ACCOUNTNUM”> <generator class=“native”/> </id> <discriminator column=“TYPE”/> <property name=“first”/> <property name=“last”/> ... <subclass name=“SavingsAccount” discriminator-value=“1”> <property name=“interestRate” column=“INTEREST”/> ... </subclass> <subclass name=“CheckingAccount” discriminator-value=“2”> <property name=“checkFee” column=“FEE”/> ... </subclass> </class> Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 50
  • 51. Oxygen Blast: Java Persistence with Hibernate Queries Hibernate supports several ways of getting objects recreated from data in the database. Hibernate also has non-object query capabilities for things like reports. Single object retrieval has already been demonstrated. session.get(Customer.class, id); Standard SQL can be used when absolutely necessary. The query capabilities are too numerous to show here, but we can give you a few examples of the options. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 51
  • 52. Oxygen Blast: Java Persistence with Hibernate HQL Hibernate Query Language (HQL) is an object oriented query language for performing queries. ANSI SQL based. Provides for parameter binding like JDBC. Examples Query q = session.createQuery(“from Customer”); List list = q.list(); //get all customers in a list Customer tom = (Customer)session.createQuery( “from Customer c where c.id=1”).uniqueResult(); //single customer Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 52
  • 53. Oxygen Blast: Java Persistence with Hibernate Criteria Queries As an alternate to HQL, Hibernate offers Criteria Queries More object oriented in their approach. Queries can be partially checked at compile time versus runtime. Examples List list = session.createCriteria(Customer.class) .add(Restrictions.eq(“gender”,’F’)).list(); //retrieve all female customers List list2 = session.createCriteria(Customer.class) .add(Restrictions.like(“name”,”D%”)) .addOrder(Order.asc(“dateOfBirth”)).list(); //all customers ordered by date of birth whose name begins with D Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 53
  • 54. Oxygen Blast: Java Persistence with Hibernate Fetching Strategies Along with fetching objects there is a problem when objects are related to other objects. When you fetch a customer, should you also fetch associated address, order, order item, etc. objects? If not, what happens when you do something like the following? Customer dave = (Customer)session.get(Customer.class, new Long(3)); dave.getAddress(); Object graphs can be quite large and complex. How much and when should objects be retrieved? Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 54
  • 55. Oxygen Blast: Java Persistence with Hibernate Proxy Objects Hibernate provides for specifying both lazy and eager fetching. When lazy fetching is specified, it provides proxy objects as stand- ins for associated objects Proxy objects get replaced by the framework when a request hits a proxy. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 55
  • 56. Oxygen Blast: Java Persistence with Hibernate Hibernate Flexibility and Extendibility Hibernate can be modified or extended. If you don’t like the way Hibernate handles a part of your persistence or you need capabilities it doesn’t offer, you can modify its functionality. Of course, it is open source, but there are also a number of extension points. Extension points include Dialects for different databases. Custom Mapping Types IdentifierGenerator Cache & CacheProvider Transaction & TransactionFactory PropertyAccessor ProxyFactory ConnectionProvider Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 56
  • 57. Oxygen Blast: Java Persistence with Hibernate Good Design As with any technology, learning Hibernate is not hard. Using it effectively takes time and practice. There are a number of design patterns and tips. Some are actually provided with the Hibernate.org documentation. Check out Hibernate’s Tips/Tricks FAQ. More background is required to discuss some of the patterns and tips/tricks. Some make good sense no matter what ORM tool is used. A few are apparent even with the knowledge gained here today. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 57
  • 58. Oxygen Blast: Java Persistence with Hibernate Layered Design Pattern Hibernate provides the means to perform persistence without code intrusion. However, this does not negate the need for appropriate data access layers. A common pattern applied to Hibernate applications is to separate layers and provide appropriate interfacing. Allows Hibernate or other ORM to be more easily replaced or extended. Provides appropriate separation of concerns. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 58
  • 59. Oxygen Blast: Java Persistence with Hibernate Design Layers Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 59
  • 60. Oxygen Blast: Java Persistence with Hibernate Service Interface & Implementation public interface CustomerService { public class CustomerServiceImpl implements public void save(Customer customer); CustomerService { public List findAll(); } private CustomerDao customerDao = new CustomerDaoHibernateImpl(); public void save(Customer customer) { customerDao.save(customer); } public List findAll() { return customerDao.findAll(); } } Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 60
  • 61. Oxygen Blast: Java Persistence with Hibernate DAO Interface and Implementation public interface CustomerDao { public class CustomerDaoHibernateImpl implements CustomerDao { public void save(Customer customer); public void save(Customer customer) { public List findAll(); Session session = null; Transaction trans = null; } try { session = HibernateUtils.getSession(); trans = session.beginTransaction(); session.save(customer); trans.commit(); HibernateUtils.releaseSession(session); } catch (Exception e) {} } public List findAll() { Session session = null; Transaction trans = null; List list = null; try { session = HibernateUtils.getSession(); trans = session.beginTransaction(); list = session.createQuery(quot;from Customer c order by c.namequot;).list(); trans.commit(); HibernateUtils.releaseSession(session); } catch (Exception e) {} return list; } Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 61 }
  • 62. Oxygen Blast: Java Persistence with Hibernate Hibernate Utils public class HibernateUtils { private static SessionFactory sessionFactory; static { sessionFactory = new Configuration().configure().buildSessionFactory(); } public static Session getSession() { return sessionFactory.openSession(); } public static void releaseSession(Session session) { session.close(); } } Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 62
  • 63. Oxygen Blast: Java Persistence with Hibernate Hibernate Tips/Tricks Get a SessionFactory early and keep it. Get Sessions and Transactions close to the unit of work and drop them. Load lazy by default (for individual objects). Use HQL or Criteria with eager fetching when subject to N+1 fetches. Hibernate offers two levels of cache. Take care when configuring either. Bags can provide horrible collection performance. If properties are only read but never updated, mark them appropriately. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 63
  • 64. Oxygen Blast: Java Persistence with Hibernate Revisiting Hibernate and EBJ Is EJB 3.0 a close Hibernate clone? Hibernate/JBoss advocates sat on the EJB 3.0 specification board. There are a lot of common threads. Actually, EJB 3.0 has borrowed from all the best ORM frameworks. In EJB 3.0, beans are now POJOs (as in Hibernate) Annotations demarcate the type of beans (session, entity, etc.) and their remoteness (remote vs. local). Gone is the need for the Home interface. Gone is the need for a deployment descriptor. Client’s use annotations and dependency injection to gain access to EJB’s JNDI is not required. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 64
  • 65. Oxygen Blast: Java Persistence with Hibernate More on EJB 3.0 A new EntityManager class manages entity beans persistent state. The EntityManager is a Hibernate Session look alike. EntityManagers can work with beans in detached state. There is better object-relational mapping capability in EJB 3.0. Better support for inheritance. Better support for polymorphism. The EJB query language is more in line with HQL. In fact, there are ways to integrate EJB 3.0 systems with Hibernate. Allowing Hibernate classes to fulfill the EJB interfaces. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 65
  • 66. Oxygen Blast: Java Persistence with Hibernate Resources www.hibernate.org Complete online documentation and Javadoc API. FAQs including tips/tricks FAQ http://theserverside.com http://www.javaranch.com http://www.gloegl.de/5.html Books Hibernate in Action (Bauer/King – Manning) Hibernate a Developer’s Notebook (Elliot – O’Reilly) Hibernate: A J2EE™ Developer's Guide (Iverson - Addison Wesley) Intertech Training – Complete Hibernate Of course!!! Come back and visit us. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 66
  • 67. Oxygen Blast: Java Persistence with Hibernate Thank You Thank you For your participation For your patience and attention For your past, current and future BUSINESS! Hopefully you learned something… I always learn from you…so thanks Remember email is like saving data (jwhite@intertech.com) Email early…email often Let me hear your questions, issues Promise to respond…may take a few days Come back and see us again Complete Hibernate Complete Java Web Development, Complete JSF, or Complete Struts Complete Java Web Services or Complete Java and XML Let us know if our consultants can help you. Copyright © Intertech, Inc. 2006 • www.Intertech.com • 800-866-9884 • Slide 67