Hibernate

1,191 views

Published on

A lab talk on Hibernate and JPA.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,191
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
59
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Hibernate

  1. 1. An Introduction to Object-Relational Mapping<br />Chris Roeder<br />1<br />Chris Roeder<br />
  2. 2. Introduction<br />Hibernate is a tool for storing object data (Java) in a relational database (MySQL, Oracle)<br />Benefits<br />Less code, less repeated code<br />Standards-based (JPA)<br />connection pooling <br />creating new db connections is expensive, reuse them<br />Hides (abstracts away) the relational database as an implementation detail<br />database portability<br />SQL is standard, most vendors offer a dialect<br />Costs<br />Not a perfect abstraction, optimizations at RDB/SQL level required <br />Motivated by work with Gully Burns at ISI and a Flash client (Flex)<br />Talk attempts introductions to ERD and OOD as well as depth<br />2<br />Chris Roeder<br />
  3. 3. Contents<br />Background<br />Relational Database Design<br />Object Oriented Design<br />Object-Relational Mapping<br />Library Dependencies<br />Meta Data<br />Hibernate, JPA<br />Etc<br />3<br />Chris Roeder<br />
  4. 4. Relational Database Design<br />Relational Database<br />The world is full of objects (rows), like objects stored in a table<br />keys (SSN, VIN, account number, Student ID, IP and MAC addresses)<br />attributes (every row in a table has the same attributes: 1st NF)<br />relationships between them<br />Datatypes have size. Often the number of characters used: Char(20), Real(10)<br />Logical Criteria for Good Design: Normalization. The attribute should depend on:<br />the key,<br />the whole key (2nd Normal Form),<br />and nothing but the key (3rd Normal Form)<br />so help me Codd. (see E.F. Codd, "A Relational Model of Data for Large Shared Data Banks", Comm. ACM 13 (6), June 1970, pp. 377-387.)<br />Joins are the process an RDB goes through to create relationships expressed in the data<br />The tables are there. The foreign keys are there, but the relationships are created dynamically.<br />This is considered an evolution over earlier Network designs that had static relationships restricting efficient use to the originally supported design.<br /> Interesting contrasts to Triple Stores and Graph Databases.<br />4<br />Chris Roeder<br />
  5. 5. RDB Example<br />Table Person ( ssn integer primary key, first char(20), last char(20) )<br />Table Car ( vin integer primary key, make char(20), model char(20), owner integer not null)<br />1234 Chris Roeder<br />1235 Bill Baumgartner<br />9876 Subaru Outback 12349877 Toyota Hylander 12359875 Sunbeam Tiger 0001<br />5<br />Chris Roeder<br />
  6. 6. RDB<br />“primary key” means that data in that column is unique<br />“not null” means you must have a value for that column<br />NULL is an “out-of-band” value distinct from 0 or the empty string<br />Example Query:<br />Select make, model, first, last from Car, Personwhere car.owner = person.ssn <br />The database filters a cross product of rows from each table by the “where” condition, “joining” them.<br />Can declare foreign key constraints (not shown) so that the database only accepts rows where the relationships hold. The 0001 for the owner of the Tiger would be invalid since there is no Person with that id.<br />6<br />Chris Roeder<br />
  7. 7. RDB: many-many relationships<br />Q: What if the car is owned by more than one person?<br />A: you could flip the relationship around: Have the person table include the VIN<br />Q: What if the car is owned by more than one person and a person can own more than on car?<br />A: you need an intermediary table, a “join table” that represents the collection of owners<br />7<br />Chris Roeder<br />
  8. 8. RDB: Join Table<br />Table Person ( ssn integer primary key, first char(20), last char(20) )<br />Table Car ( vin integer primary key, make char(20), model char(20))<br />Table CarPerson ( ssn integer, vin integer )<br />9876 Subaru Outback<br />9877 Toyota Hylander<br />9875 Sunbeam Tiger<br />1234 9876<br />1235 9877<br />1234 9875<br />1235 9875<br />1234 Chris Roeder<br />1235 Bill Baumgartner<br />Select make, model, first, last from Car c, Person p, CarPerson cpwhere p.ssn = cp.ssn and cp.vin = c.vin <br />A Join Table is an implementation of a many-many relationship between Car and Person.<br />Doesn’t appear in “logical” models, but does appear in “physical” models<br />8<br />Chris Roeder<br />
  9. 9. Getting Data from DB to Java:JDBC Example(Java DataBase Connectivity)<br />static List<Restaurant> selectRestaurants() throws SQLException {<br /> List<Restaurant> restaurants = new ArrayList<Restaurant>();<br /> stmt = conn.createStatement();<br /> ResultSet results = stmt.executeQuery("select * from " + tableName);<br /> ResultSetMetaData rsmd = results.getMetaData();<br /> int numberCols = rsmd.getColumnCount();<br /> while(results.next()) {<br /> // get columns by number<br /> int id = results.getInt(1); <br /> // or by name: results.getInt("id");<br /> String restName = results.getString(2);<br /> String cityName = results.getString(3);<br /> System.out.println(id + "tt" + restName + "tt" + cityName);<br /> //Map from database into the object <br /> Restaurant r = new Restaurant(restName, cityName);<br /> restaurants.add(r);<br /> }<br /> results.close();<br /> stmt.close();<br /> return restaurants;<br />}<br />9<br />Chris Roeder<br />
  10. 10. Contents<br />Background<br />Relational Database Design<br />Object Oriented Design<br />Object-Relational Mapping<br />Library Dependencies<br />Meta Data<br />Hibernate, JPA<br />Etc<br />10<br />Chris Roeder<br />
  11. 11. Object Oriented Design <br />OOA/OOD: Object Oriented Analysis and Design<br />The world is full of objects made up of functions and data.<br />The data (members) are encapsulated.<br />Only the object’s funtions (methods) can access the (private) members.<br />Objects can be composed or aggregated of others: has-a<br />Objects can defined as extensions of others<br />Inheritance, is-a<br />Model data and behavior, Normalize using data and behavior (not just data)<br />Member functions produce “Side Effects” by changing the state of the object, potentially changing future invocations of a function called with the same arguments<br />Considered evil by FP zealots<br />Realistically a bane to concurrent programming<br />11<br />Chris Roeder<br />
  12. 12. OOD Example<br />Vehicle<br />Location<br />Occupants<br />Car is-a (extends, inherits from) Vehicle<br />Has Engine<br />Has Wheel(s) (relationship to Wheel is one-many)<br />Function Drive() modifies Location<br />Owner<br />Has Vehicle(s) (one-many)<br />12<br />Chris Roeder<br />
  13. 13. OOD: many-many relationships<br />Many-many relationships in OOD are like what you would think of in code:<br />Two classes, each with a list of references, one for either direction<br />No join table<br />Relationship doesn’t have to be symmetrical<br />It could just be that one side has a list of references to the other<br />It’s many-many because of what the list can contain<br />13<br />Chris Roeder<br />
  14. 14. OOD Code Example(incomplete psuedo code)<br />Public class Owner {<br /> private List<Vehicle> vehicles;<br />}<br />Public class Vehicle {<br /> private GPSCoords location; <br />}<br />Public class Car extends Vehicle {<br /> public void drive() { location = { 38, 140}; <br />}<br />// note: an Owner can access their Car, but a Car cannot access it’s owner<br />14<br />Chris Roeder<br />
  15. 15. Contents<br />Background<br />Relational Database Design<br />Object Oriented Design<br />Object-Relational Mapping<br />Library Dependencies<br />Meta Data<br />Hibernate, JPA<br />Etc<br />15<br />Chris Roeder<br />
  16. 16. ORM: Object Relational Mapping<br />Store data in an RDB, Use it in Java<br />In an organized fashion, with minimal “boilerplate” setup code that is repeated with every project<br />Bridge Differences in Design<br />Join table in OO?<br />Inheritance in RDB?<br />Different Datatypes:<br />Integer, String, Double <br />vs Integer(10), varchar(50), real(10)<br />Moving between the two means you have to deal with this problem: impedance mismatch<br />16<br />Chris Roeder<br />
  17. 17. ORM: Impedance Mismatch data types<br /><ul><li>Real(8)   Double</li></ul>Both 10,000,001 and 80,000,001 fit into Real(8)<br />Only 10,000,001 fits into Float (without rounding)<br />The 80,000,001 will be rounded to 8.0*10^7, losing the last 1.<br />Varchar(100)  String<br />can have ‘n’, but it’s finite. Java is finite too, but not as strictly.<br />Example:<br />Varchar(10) can hold “foobar”, but not “supercalifragilistic”<br />Java: String word=“supercalifragilistic” is ok<br />17<br />Chris Roeder<br />
  18. 18. ORM: Impedance Mismatchrelationships<br />RDB needs join tables for many:many<br />Java doesn’t<br />RDB relationships are bidirectional<br />Unidirectional in Java. Specify both if you need both<br />18<br />Chris Roeder<br />
  19. 19. ORM: Impedance MismatchInheritance<br />Java can have two classes that inherit from a base<br />SUV and SportsCar inherit from Car<br />Car lists common attributes and behaviors<br />SUV and SportsCar get them, but they aren’t duplicated (in code).<br />How to represent this in an RDB?<br />2 tables that include specific and general<br />3 tables and some fancy joining<br />Chris Roeder<br />19<br />
  20. 20. Contents<br />Background<br />Relational Database Design<br />Object Oriented Design<br />Object-Relational Mapping<br />Library Dependencies<br />Meta Data<br />Hibernate, JPA<br />Etc<br />20<br />Chris Roeder<br />
  21. 21. Library Dependencies, Flexibility <br />Software Engineering involves flexibility.<br />You may want to change databases, or ORM tools (easily).<br />Older tools required the model’s entity classes (Car, Person, RepairShop, etc.) to import ORM packages into the Java source code.<br />Creating a dependency on that library (jar)<br />Imagine doing this for 100 entities.<br />Newer tools don’t. They allow you to use POJOs…<br />21<br />Chris Roeder<br />
  22. 22. POJO (Plain Old Java Object)<br />“Plain” means “not an EJB (enterprise java bean)”<br />Martin Fowler, et. al.<br />EJB’s are complicated, POJOs not<br />The “Car” class is about cars and how they change: <br />make, model, year, color, owner<br />mileage, fuel level, position, passengers, cargo, velocity<br />Not about how it is stored between application invocations or how it is “persisted”<br />A “plain” java object, a POJO, does not import persistence library classes, so they can be easily changed.<br />A framework that uses POJOs may be less restrictive<br />22<br />Chris Roeder<br />
  23. 23. Contents<br />Relational Database Design<br />Object Oriented Design<br />Object-Relational Mapping<br />Library Dependencies<br />Meta Data<br />Hibernate, JPA<br />Etc<br />23<br />Chris Roeder<br />
  24. 24. Meta Data<br />The ORM tool needs to know more about the POJO than normal Java code would tell it.<br />No resorting to naming conventions.<br />(Ruby on Rails does so: Convention over Configuration)<br />What s the table name?<br />Which member is the key field?<br />What are the details of the relationships (one-many, foreign key field, which is the join table)?<br />This does not include connection information.<br />24<br />Chris Roeder<br />
  25. 25. Expressing Meta Data<br />Older ORM’s used an XML file to desribe the additional details. This has some drawbacks:<br />Now your class is described in two places.<br />XML meta data grew quite cumbersome<br />An evolution was to put comments in that had the meta-data in the style of Javadoc @author attributes and generate code : Xdoclet (2002-2004)<br />Java 1.5 included the annotations facility (jsr-175 2002)<br />25<br />Chris Roeder<br />
  26. 26. Example POJO With Annotations<br />@Entity<br />public class Person {<br /> private Long id;<br /> @Id<br /> @GeneratedValue(strategy = GenerationType.IDENTITY)<br /> public Long getId() { <br />return id;<br /> } <br /> // snip<br /> @ManyToMany(cascade=CascadeType.ALL,mappedBy="authors",targetEntity=Publication.class)<br /> public Set<Publication> getPublications() {<br /> return publications;<br /> }<br />} <br />26<br />Chris Roeder<br />
  27. 27. Irony<br />The desire for simplicity in POJOs rejects “invasive” technologies<br />Having imports from the ORM is seen as restrictive<br />Precursors to Java Annotations, either XML files or pre-processed annotations as in Xdoclet are non-invasive.<br />The POJO must import the annotation classes<br />So it’s not a pure POJO anymore.<br />27<br />Chris Roeder<br />
  28. 28. Contents<br />Relational Database Design<br />Object Oriented Design<br />Object-Relational Mapping<br />Library Dependencies<br />Meta Data<br />Hibernate, JPA<br />28<br />Chris Roeder<br />
  29. 29. Hibernate, JPA<br />Hibernate is an ORM<br />JPA (Java Persistence Architecture) is a spec.<br />Shared, supported and implemented by many vendors, not just Hibernate<br />Came after Hibernate<br />Hibernate has it’s own API<br />Hibernate supports/implements JPA<br />Others (Toplink) support JPA as well<br />29<br />Chris Roeder<br />
  30. 30. Hibernate Code Example<br />session = sessionFactory.openSession();<br />session.beginTransaction();<br />@SuppressWarnings("unchecked")<br />List<Restaurant> result = (List<Restaurant>) session.createQuery( "from Restaurant" ).list();<br />assertEquals(3, result.size());<br />for ( Restaurant event : (List<Restaurant>) result ) {<br /> System.out.println( "Restaurant: " + event.getId() + ", " + event.getCity() + ", " + event.getRestaurant() );<br />}<br />session.getTransaction().commit();<br />session.close();<br />Chris Roeder<br />30<br />
  31. 31. Code Comparison<br />@SuppressWarnings("unchecked")<br />List<Restaurant> result = (List<Restaurant>) session.createQuery( "from Restaurant" ).list();<br />Chris Roeder<br />31<br />Hibernate<br />JDBC<br />List<Restaurant> restaurants = new ArrayList<Restaurant>();<br />ResultSet results = stmt.executeQuery("select * from " + tableName);<br /> while(results.next()) {<br /> // get columns by number<br /> int id = results.getInt(1); // or by name: results.getInt("id");<br /> String restName = results.getString(2);<br /> String cityName = results.getString(3);<br /> Restaurant r = new Restaurant(restName, cityName);<br /> restaurants.add(r);<br /> }<br />
  32. 32. Hibernate Configuration<br /> <hibernate-configuration><br /> <session-factory><br /> <!-- Database connection settings --><br /> <property name="connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property><br /> <property name="connection.url">jdbc:derby:myDB;create=true;user=me;password=mine</property><br /> <property name="connection.username">me</property><br /> <property name="connection.password">mine</property><br /> <!-- JDBC connection pool (use the built-in) --><br /> <property name="connection.pool_size">1</property><br /> <!-- SQL dialect --><br /> <property name="dialect">org.hibernate.dialect.DerbyDialect</property><br /> <!-- Echo all executed SQL to stdout --><br /> <property name="show_sql">true</property><br /> <!--<mapping resource="org/hibernate/tutorial/hbm/Event.hbm.xml"/>--><br /> <mapping class="edu.ucdenver.ccp.uimatracking.Restaurant"/><br /> </session-factory><br /></hibernate-configuration><br />Chris Roeder<br />32<br />
  33. 33. JPA, Hibernate Comparison<br />JPA<br />List<Restaurant> result = entityManager.createQuery("from Restaurants").getResultList();<br />Hibernate<br />List<Restaurant> result = (List<Restaurant>) session.createQuery( "from Restaurants" ).list();<br />Chris Roeder<br />33<br />
  34. 34. JPA Configuration<br /><persistence-unit name="edu.ucdenver.ccp.uimatracking.jpademo" transaction-type="RESOURCE_LOCAL"><br /><class>edu.ucdenver.ccp.uimatracking.Restaurant</class><br /><properties><br /> <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/><br /> <property name="javax.persistence.jdbc.user" value="me"/><br /> <property name="javax.persistence.jdbc.password" value="mine"/><br /> <property name="javax.persistence.jdbc.url" value="jdbc:derby:myDB;create=true"/><br /> <property name="hibernate.show_sql" value="true"/><br /> <property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/><br /> <!--<property name="hibernate.hbm2ddl.auto" value="update" /> --><br /> </properties><br /> <!-- <jta-data-source>java:/DefaultDS</jta-data-source>--><br /></persistence-unit><br />Chris Roeder<br />34<br />
  35. 35. Contents<br />Relational Database Design<br />Object Oriented Design<br />Object-Relational Mapping<br />Library Dependencies<br />Meta Data<br />Hibernate, JPA<br />Etc<br />Chris Roeder<br />35<br />
  36. 36. Sample Code Project <br />“HibernateDemo”<br />In SVN under projects<br />Maven-driven<br />Uses Derby database in embedded mode<br />No db installation required<br />Inlcudes samples:<br />JDBC<br />Hibernate<br />JPA<br />Chris Roeder<br />36<br />
  37. 37. Relationships (TBC)<br />Relationships<br />One-one<br />-one-many<br />Many-many<br />Chris Roeder<br />37<br />
  38. 38. Optimizations (TBC)<br />Query Optimizations<br />Application joins<br />Limiting the size and depth of the resulting object graph<br />Chris Roeder<br />38<br />
  39. 39. Further CodeTalk Topics<br />Object Oriented Design <br />Contrast to Functional Decomposition<br />Contrast to Functional Programming,<br /> immutability, side effects<br />Relational Design<br />Joins: cost or benefit?<br />Advanced ORM Relationship Modelling<br />ORM Performance and Optimization<br />Chris Roeder<br />39<br />
  40. 40. References<br />Hibernate in Action, Christian Bauer, Gavin King, Manning<br />Pro JPA 2, Merrick Shincariol, Apress<br />http://docs.jboss.org/hibernate/core/3.6/quickstart/en-US/html_single/#hibernate-gsg-tutorial-basic-entity<br />http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#tutorial-firstapp-firstclass<br />http://blog.springsource.com/2006/05/30/getting-started-with-jpa-in-spring-20/<br />Chris Roeder<br />40<br />
  41. 41. Thank You<br />Gully Burns<br />Having a project that interfaces with JPA<br />Yuriy <br />Early review<br />Bill <br />Organizing, motivating<br />CCP<br />attention<br />Chris Roeder<br />41<br />

×