03 Object Relational Mapping


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

03 Object Relational Mapping

  1. 1. Object/Relational Mapping Solving the structural paradigm mismatch
  2. 2. Creating a Domain Model <ul><li>An object-oriented domain model </li></ul><ul><ul><li>captures the entities with the help of the business experts </li></ul></ul><ul><ul><li>concrete things like User, Item, Category, abstract like PricingAlgorithm </li></ul></ul><ul><ul><li>developers create an object model of the problem domain </li></ul></ul><ul><ul><li>can be only a mental model or elaborate as UML diagrams </li></ul></ul><ul><ul><li>we may also have a relational data model, designed using E / R modelling </li></ul></ul><ul><ul><li>a relational schema, or a model defined in some CASE tool </li></ul></ul>Item 0..* User 0..* sells Category
  3. 3. Our example application <ul><li>CaveatEmptor is an online auction system – we have the following domain model: </li></ul><ul><li>Do we need any special programming model to implement this domain model in Java? </li></ul>Item 0..* User 0..* sells Bid 0..* 0..* Address 0..* BillingDetails CreditCard BankAccount home billing 0..* Category
  4. 4. Writing POJOs <ul><li>We implement our domain model persistent classes with POJOs </li></ul><ul><ul><li>loosely follow the JavaBean specification (actually, just about any Java class will do) </li></ul></ul><ul><ul><li>we usually provide accessor methods for property management with (any visibility), but this is not required </li></ul></ul><ul><ul><li>no-argument constructor (with at least package visibility) is required </li></ul></ul><ul><ul><li>better to make the class and all public methods non-final </li></ul></ul><ul><ul><li>declare the class Serializable if you need to transport data between tiers </li></ul></ul>POJO Best Practices are actually requirements of Hibernate for persistent classes.
  5. 5. A simple POJO public class User implements Serializable { private String username; private Address address; public User() {} public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Address getAddress() { return address;} public void setAddress(Address address) { this.address = address; } public MonetaryAmount calcShippingCosts(Address from) { ... } }
  6. 6. Adding logic to accessor methods <ul><li>We can also add certain kinds of logic - especially validation - to our accessor methods: </li></ul><ul><li>Let’s create the mapping for User ... </li></ul>public class User { private String firstname; ... public void setFirstname(String firstname) throws InvalidNameException { if ( !StringUtil.isCapitalizedName(firstname) ) throw new InvalidNameException(firstname); this.firstname = firstname; ) ... }
  7. 7. Class mapping <ul><li>We use the <class> element for each persistent class </li></ul><ul><ul><li>requires class name, table and schema are optional </li></ul></ul><ul><ul><li>by default, all columns are inserted and updated </li></ul></ul><ul><ul><li>override with dynamic insert and update, no SQL generation on startup </li></ul></ul><hibernate-mapping package=&quot;org.hibernate.auction.model&quot; schema=&quot;AUCTION&quot;> <class name=&quot;User&quot; table=&quot;USER&quot; dynamic-insert=&quot;true&quot; dynamic-update=&quot;true&quot;> </class> ... </hibernate-mapping>
  8. 8. Property mapping <ul><li>We use <property> for each property of our class: </li></ul><ul><li>If your property and class names are special (prefix, suffix, etc.), implement a Hibernate NamingStrategy . </li></ul><!- An immutable property --> <property name=&quot;orderNumber&quot; column=&quot;ORDER_NR&quot; type=&quot;string&quot; not-null=&quot;true&quot; access=&quot;field&quot; update=&quot;false&quot;/> <!-- A derived property (read only) --> <property name=&quot;totalIncludingTax&quot; formula=”PRICE + PRICE * TAX_RATE&quot; type=&quot;big_decimal&quot;/>
  9. 9. Writing persistent classes <ul><li>Entity associations are also represented as properties: </li></ul>0..* public class Category { private String name; private Category parentCategory ; private Set childCategories = new HashSet(); Set getChildCategories() { return childCategories; } void setChildCategories(Set categories) { childCategories = categories; } public Category getParentCategory() { return parentCategory(); } void setParentCategory(Category category) { parentCategory = category; } } Category
  10. 10. Optimizing association handling <ul><li>To create an association, we have to </li></ul><ul><ul><li>set the parentCategory of a child </li></ul></ul><ul><ul><li>the child must be added to the childCategories of the parent </li></ul></ul><ul><ul><li>we don't have some container-managed relationship handling! </li></ul></ul><ul><li>We will come back to association mappings soon…. </li></ul>public void addChildCategory(Category child) { // Be defensive! if (child == null) throw new IllegalArgumentException(&quot;null Child&quot;); // Ensure multiplicity if ( child.getParent() != null ) child.getParent().getChildCategories().remove(child); child.setParent(this); getChildCategories().add(child); }
  11. 11. Primary keys <ul><li>The primary key for our tables should be </li></ul><ul><ul><li>unique: no duplicate values ever </li></ul></ul><ul><ul><li>constant: value is never updated </li></ul></ul><ul><ul><li>required: never null </li></ul></ul><ul><li>Types of primary keys: </li></ul><ul><ul><li>natural key: an attribute that is unique by virtue of its business meaning (any composite key is a natural key) </li></ul></ul><ul><ul><li>surrogate key: an attribute generated by the system, with no meaning to the user, and no business semantics </li></ul></ul><ul><li>For new systems, we recommend the use of surrogate keys everywhere , since this strategy makes schema evolution simpler – true natural keys are hard to find! </li></ul>
  12. 12. Database identity in Hibernate <ul><li>We add an identifier property to persistent classes </li></ul><ul><ul><li>the value of that property is the primary key value </li></ul></ul><ul><ul><li>the name should always be the same for all classes, e.g. id </li></ul></ul><ul><li>Should the identifier property be public? </li></ul><ul><ul><li>if we use the identifier outside of persistence, e.g. in web applications </li></ul></ul><ul><ul><li>it is a convenient “handle” to a particular instance </li></ul></ul><ul><ul><li>lookup by identifier is an especially efficient operation in Hibernate </li></ul></ul><ul><ul><li>we usually have a public getter and a private setter </li></ul></ul>public class Category { private Long id = null; public Long getId() { return this.id; } private void setId(Long id) { this.id = id; } }
  13. 13. Identity mapping <ul><li>Identifier property mappings </li></ul><ul><ul><li>the identifier property type may be any Hibernate type </li></ul></ul><ul><ul><li>the identifier generation strategy may be customized </li></ul></ul><ul><ul><li>identifier properties are actually optional, but strongly recommended (if you don’t have an identifier property, just omit name in the mapping) </li></ul></ul><class name=&quot;Category&quot; table=&quot;CATEGORY&quot;> <id name=&quot;id&quot; column=&quot;CATEGORY_ID&quot; type=&quot; long &quot;> <generator class=&quot; native &quot;/> </id> ... </class>
  14. 14. Identifier generation strategies <ul><li>increment </li></ul><ul><ul><li>incrementing value, unique to the JVM ( long, short, int ) </li></ul></ul><ul><li>native </li></ul><ul><ul><li>picks other strategies, depending on the database capabilities ( long, short, int ) </li></ul></ul><ul><li>identity </li></ul><ul><ul><li>identity column types in DB2, MS SQL Server, Sybase, MySQL, etc ( long, short, int ) </li></ul></ul><ul><li>sequence </li></ul><ul><ul><li>incrementing sequence in DB2, PostgreSQL, Oracle, etc ( long, short, int ) </li></ul></ul><ul><li>hilo </li></ul><ul><ul><li>high- and low-value algorithm, unique to database instance ( long, short, int ) </li></ul></ul><ul><li>uuid.hex </li></ul><ul><ul><li>Hibernate UUID algorithm, unique to a subnet ( String ) </li></ul></ul><ul><li>guid </li></ul><ul><ul><li>database GUID algorithm for MySQL and MS SQL Server, introduced in Hibernate3 ( String ) </li></ul></ul><ul><li>assigned </li></ul><ul><ul><li>the application assigns identifier values </li></ul></ul>
  15. 15. Hibernate type system <ul><li>Entity types (e.g. User , Category , Item ) </li></ul><ul><ul><li>own database identity (primary key) </li></ul></ul><ul><ul><li>references are foreign keys </li></ul></ul><ul><ul><li>own lifecycle independent of other entities </li></ul></ul><ul><ul><li>shared references are possible </li></ul></ul><ul><ul><li>usually user-defined classes </li></ul></ul><ul><li>Value types (e.g. Address, String, Integer ) </li></ul><ul><ul><li>no database identity </li></ul></ul><ul><ul><li>lifespan of value object is bound to containing entity </li></ul></ul><ul><ul><li>built-in JDK types and user-defined types </li></ul></ul>
  16. 16. Built-in value types <ul><li>integer, long, short, float, double, character, byte, boolean, yes_no, true_false </li></ul><ul><ul><li>map Java primitives or wrapper classes </li></ul></ul><ul><li>string </li></ul><ul><ul><li>maps java.lang.String </li></ul></ul><ul><li>date, time, timestamp </li></ul><ul><ul><li>mappings for java.util.Date and subclasses </li></ul></ul><ul><li>calendar, calendar_date </li></ul><ul><ul><li>mappings for java.util.Calendar </li></ul></ul><ul><li>big_decimal </li></ul><ul><ul><li>maps java.math.BigDecimal </li></ul></ul><ul><li>locale, timezone, currency, class </li></ul><ul><ul><li>mappings for miscellaneous JDK classes </li></ul></ul><ul><li>binary, text </li></ul><ul><ul><li>mappings for binary (byte array) or text (string) data </li></ul></ul><ul><li>blob, clob </li></ul><ul><ul><li>mappings for java.sql.Blob, java.sql.Clob </li></ul></ul><ul><li>serializable </li></ul><ul><ul><li>maps a serializable Java object to a binary data type – do not use this! </li></ul></ul>
  17. 17. Composition in our object model <ul><li>Classes can have a composition relationship: </li></ul>User Address home billing class User { private Long id; private Address homeAddress; private Address billingAddress; } class Address { private String street; private String zipcode; private String city; }
  18. 18. Mapping components <ul><li>We sometimes map the composed object to the same table </li></ul><ul><ul><li>USER table with STREET , ZIPCODE , CITY columns </li></ul></ul><class name=&quot;User&quot; table=&quot; USER &quot;> <id name=&quot;id&quot; column=&quot;USER_ID&quot;> <generator class=&quot;native&quot;/> </id> <component name=&quot;homeAddress&quot; class=&quot;Address&quot;> <property name=&quot;street&quot; column=&quot; HOME_STREET &quot; not-null=&quot;true&quot;/> <property name=&quot;city&quot; column=&quot; HOME_CITY &quot; not-null=&quot;true&quot;/> <property name=&quot;zipcode&quot; column=&quot; HOME_ZIPCODE &quot; not-null=&quot;true&quot;/> </component> ... </class>
  19. 19. Bidirectional component mapping <ul><li>We can even make the relationship bidirectional: </li></ul><ul><ul><li>we can't have shared references to Address objects </li></ul></ul><ul><ul><li>a null homeAddress will be represented as null values in all columns </li></ul></ul><component name=&quot;homeAddress&quot; class=&quot;Address&quot;> <parent name=&quot;user&quot;/> <property name=&quot;street&quot; column=&quot; HOME_STREET &quot; not-null=&quot;true&quot;/> <property name=&quot;city&quot; column=&quot; HOME_CITY &quot; not-null=&quot;true&quot;/> <property name=&quot;zipcode&quot; column=&quot; HOME_ZIPCODE &quot; not-null=&quot;true&quot;/> </component>
  20. 20. Class inheritance hierarchies <ul><li>Three strategies to map an inheritance hierarchy: </li></ul><ul><ul><li>table per concrete class: no polymorphism </li></ul></ul><ul><ul><li>table per class hierarchy: denormalization and discriminator </li></ul></ul><ul><ul><li>table per subclass: using &quot;has a&quot; foreign key relationships </li></ul></ul>BillingDetails CreditCard BankAccount
  21. 21. Table per concrete class mapping <ul><ul><li>polymorphic associations to BillingDetails are difficult </li></ul></ul><ul><ul><li>a query against the superclass is several SELECTs </li></ul></ul><ul><ul><li>changes to the superclass require multiple table changes </li></ul></ul><ul><ul><li>no special Hibernate mapping, just <class> </li></ul></ul><< table >> CREDIT_CARD CREDIT_CARD_ID << PK >> OWNER NUMBER TYPE EXP_DATE << table >> BANK_ACCOUNT BANK_ACCOUNT_ID << PK >> OWNER NUMBER BANK_NAME BANK_SWIFT
  22. 22. Table per class hierarchy <ul><ul><li>note the type discriminator column </li></ul></ul><ul><ul><li>best performance, polymorphic queries and associations </li></ul></ul><ul><ul><li>subclass columns must be nullable! </li></ul></ul><ul><ul><li>we use the Hibernate <subclass> mapping </li></ul></ul><< table >> BILLING_DETAILS BILLING_DETAILS_ID << PK >> BILLING_TYPE << discriminator >> OWNER NUMBER CREDIT_CARD_TYPE CREDIT_CARD_EXP_DATE BANK_ACCOUNT_NAME BANK_ACCOUNT_SWIFT
  23. 23. Mapping a class hierarchy to a single table <ul><ul><li><subclass> elements can be nested </li></ul></ul><ul><ul><li>mapping strategy has to be used for all classes in the sub-hierarchy </li></ul></ul><class name=&quot;BillingDetails&quot; table=&quot;BILLING_DETAILS&quot;> <id name=&quot;id&quot; column=&quot;BILLING_DETAILS_ID&quot;> <generator class=&quot;native&quot;/> </id> <discriminator column=&quot;BILLING_TYPE&quot;/> <property name=&quot;name&quot; column=&quot;OWNER&quot;/> ... <subclass name=&quot;CreditCard&quot; discriminator-value=&quot;CC&quot; > <property name=&quot;type&quot; column=&quot;CREDIT_CARD_TYPE&quot;/> ... </subclass> ... </class>
  24. 24. Table per subclass <ul><ul><li>normalized model </li></ul></ul><ul><ul><li>polymorphic associations even to particular subclasses </li></ul></ul><ul><ul><li>we use the Hibernate <joined-subclass> mapping </li></ul></ul><< table >> CREDIT_CARD CREDIT_CARD_ID <<PK>> <<FK>> TYPE EXP_DATE << table >> BANK_ACCOUNT BANK_ACCOUNT_ID <<PK>> <<FK>> BANK_NAME BANK_SWIFT << table >> BILLING_DETAILS BILLING_DETAILS_ID <<PK>> OWNER NUMBER
  25. 25. Mapping a joined subclass to normalized tables <ul><ul><li><joined-subclass> can be nested, but not <subclass> </li></ul></ul><ul><ul><li>difficult to implement by hand </li></ul></ul><ul><ul><li>ad hoc reporting might be more complex </li></ul></ul><class name=&quot;BillingDetails&quot; table=&quot;BILLING_DETAILS&quot;> <id name=&quot;id&quot; column=&quot;BILLING_DETAILS_ID&quot;> <generator class=&quot;native&quot;/> </id> <property name=&quot;name&quot; column=&quot;OWNER&quot;/> ... <joined-subclass name=&quot;CreditCard&quot; > <key column=&quot;CREDIT_CARD_ID&quot;/> <property name=&quot;type&quot; column=&quot;CREDIT_CARD_TYPE&quot;/> ... </joined-subclass> ... </class>
  26. 26. Class associations <ul><li>A bidirectional one-to-many entity association: </li></ul><ul><li>Managed associations: </li></ul><ul><ul><li>a change to one side is immediately reflect on the other side </li></ul></ul><ul><ul><li>e.g. bid.setItem(item) executes item.getBids().add(bid) </li></ul></ul><ul><ul><li>used with container-managed relationships (CMR) in EJB/CMP </li></ul></ul><ul><li>POJOs do not have automatically managed associations! </li></ul><ul><ul><li>the common Java semantics apply </li></ul></ul><ul><ul><li>we have to manually set both &quot;ends&quot; of the &quot;link&quot; </li></ul></ul><ul><ul><li>Hibernate doesn't interfere with POJO semantics! </li></ul></ul>Item Bid 0..*
  27. 27. The tables of this association mapping << table >> ITEM ITEM_ID <<PK>> NAME PRICE ... << table >> BID BID_ID <<PK>> ITEM_ID <<FK>> AMOUNT ... PRICE NAME ITEM_ID 1 2 3 Bar Foo Baz 2.00 50.00 1.00 ITEM AMOUNT ITEM_ID BID_ID 1 2 3 1 1 2 10.00 20.00 55.00 BID
  28. 28. Mapping a unidirectional association <ul><ul><li>The column ITEM_ID is a FK to the PK of the ITEM table. </li></ul></ul>class Bid { private Item item; public void setItem(Item i) { this.item = i; } public Item getItem() { return item; } } <class name=&quot;Bid&quot; table=&quot;BID&quot;> ... <many-to-one name=&quot;item&quot; class=&quot;Item&quot; column=&quot;ITEM_ID&quot; not-null=&quot;true&quot;/> </class>
  29. 29. Making the association bidirectional <ul><ul><li>The key element refers to the ITEM_ID column in the BID table. </li></ul></ul>class Item { private Set bids = new HashSet(); public void getBids() { return bids; } public void addBid(Bid b) { this.bids.add(b) b.setItem(this) // Manage association! } } <class name=&quot;Item&quot; table=&quot;ITEM&quot;> ... <set name=&quot;bids&quot;> <key column=&quot;ITEM_ID&quot;/> <one-to-many class=&quot;Bid&quot;/> </set> </class>
  30. 30. The big problem <ul><li>We have referenced the ITEM_ID in two mappings </li></ul><ul><ul><li>At runtime, we have two in-memory representations of this associtaion, the item property of the Bid and the bids of the Item . Suppose we modify this association: </li></ul></ul>Hibernate does not transparently detect the fact that the two changes refer to the same database column, since at this point we have done nothing to indicate that this is a bidirectional association. item.getBids().add(newBid); newBid.setItem(item);
  31. 31. Making the association bidirectional <ul><li>We have to declare one end as inverse: </li></ul><ul><ul><li>changes to the inverse end will be ignored! </li></ul></ul><ul><ul><li>without inverse=“true” , Hibernate would try to issue two UPDATE statements </li></ul></ul><class name=&quot;Item&quot; table=&quot;ITEM&quot;> ... <set name=&quot;bids&quot; inverse=&quot;true&quot; > <key column=&quot;ITEM_ID&quot;/> <one-to-many class=&quot;Bid&quot;/> </set> </class>
  32. 32. Mapping collections vs Java collections Persists an unordered,non-unique many-to-many collection using a surrogate key. java.util.List idbag Persists an indexed, non-unique collection of primitive values N/A primitive-array Persists an indexed, non-unique collection of values or objects N/A array Persists an unordered, non-unique collection of values or objects java.util.List bag Persists an ordered,non-unique collection of values or objects java.util.List list Persists a collection of key/value pairs java.util.Map map Persists an unordered,unique collection of values or objects java.util.Set set Description Java Collection Type Hibernate Collection Type
  33. 33. One-to-many association <hibernate-mapping package=“demo”> <class name=“Event” table=“events”> … . <set name=“speakers”> <key column=“event_id”/> <one-to-many class=“Speaker”/> </set> <set name=“attendees”> <key column=“event_id”/> <one-to-many class=“Attendee”/> </set> … . </class> </hibernate-mapping> public class Event { private Set speakers; private set attendees; public void setSpeakers(Set speakers) { this.speakers=speakers;} public set getSpeakers() {return this.speakers;} public void setAttendees(Set attendees) { this.attendees=attendees;} public set getAttendees() {return this.attendees;}
  34. 34. One-to-many events events events attendees id bigint(pk) id bigint (pk) event_id bigint (fk) A one-to-many association from events to attendees
  35. 35. Many-to-many <ul><li>Suppose Attendees can attend more than one Event. This is a </li></ul><ul><li>Many-to-many mapping for the set of Attendees: </li></ul><ul><li><set name=“attendees” table=“event_attendees”> </li></ul><ul><li><key column=“event_id”> </li></ul><ul><li><many-to-many column=“attendee_id” class=“Attendee”/> </li></ul><ul><li></set> </li></ul>
  36. 36. many-to-many events events events event_attendees id bigint(pk) event_id bigint (fk) attendee_id bigint (fk) A many-to-many table schema from events to attendees events events attendees id bigint(pk)
  37. 37. Persisting collections of values <ul><li>The below mapping definition for a persistent set of Integers </li></ul><ul><li><set name=“ratings” table=“event_ratings”> </li></ul><ul><li><key column=“event_id”/> </li></ul><ul><li><element column=“rating” type=“integer” </li></ul><ul><li></set> </li></ul><ul><li>The table attribute defines the event_ratings table, which is </li></ul><ul><li>Used to store the values. </li></ul>
  38. 38. Lists <ul><li>Unlike Set, Lists can contain duplicate elements. Since Lists are </li></ul><ul><li>Indexed, meaning that contained elements are stored at a specific </li></ul><ul><li>Location in the List, you need to define a <list-index> element: </li></ul><ul><li><list name=“speaker”> </li></ul><ul><li><list-index column=“speaker_index”/> </li></ul><ul><li><key column = “event_id”/> </li></ul><ul><li><one-to-many class=“Speaker”/> </li></ul><ul><li></list> </li></ul>
  39. 39. Maps <ul><li>Maps store entries in key/value pairs, meaning that we retrieve the </li></ul><ul><li>Value by looking up the associated key. </li></ul><ul><li><map name=“speakers”> </li></ul><ul><li><map-key column=“speakers_index” type=“string” length=“20”/> </li></ul><ul><li><key column=“event_id”/> </li></ul><ul><li><one-to-many class=“speaker”/> </li></ul><ul><li></map> </li></ul><ul><li>Inserting elements into the map, use a String for the key </li></ul><ul><li>Map speakers = new HashMap(); </li></ul><ul><li>speakers.put(“speakers1”, new Speaker()); </li></ul><ul><li>speakers.put(“speakers2”,new Speaker()); </li></ul><ul><li>Event event = new Event(); </li></ul><ul><li>event.setSpeakers(speakers); </li></ul>
  40. 40. Bags <ul><li>To store a collection of objects without worrying about ordering </li></ul><ul><li>Or duplicate elements. This is where Bags come in : </li></ul><ul><li><bag name=“speakers”> </li></ul><ul><li><key column=“event_id”/> </li></ul><ul><li><one-to-many class=“Speaker”/> </li></ul><ul><li></bag> </li></ul><ul><li>For the javabean’s perspective, the collection of Speakers is a List. </li></ul><ul><li>Import java.util.List; </li></ul><ul><li>Public class Event </li></ul><ul><li>{ </li></ul><ul><li>Private List speakers; </li></ul><ul><li>Public void setSpeakers(List speakers) </li></ul><ul><li>{ this.speakers = speakers;} </li></ul><ul><li>Public List getSpeakers() { return this.speakers;} } </li></ul><ul><li>However, using a Bag for Hibernate means you don’t need to explicitly create an index column. </li></ul><ul><li>Set and Bag both doesn’t require an index column, but remember that a Set can’t contain duplicate elements, whereas Bags can </li></ul>
  41. 41. idbags <ul><li>Suppose we have a many-to-many association between Events and Speakers. Speakers can belong to the same Event multiple times, so we can’t use a Set. </li></ul><ul><li>We also need to ensure fast and efficient access to the many-to-many table event_speakers. We really need to be able to assign a primary key to the event_speakers table. This is where idbags come in: </li></ul><ul><li><idbag name=“speakers” table=“event_speakers” </li></ul><ul><li>lazy=“true” cascade=“all”> </li></ul><ul><li><collection-id type=“long” column=“event_speakers_id”> </li></ul><ul><li><generator-class=“native”/> </li></ul><ul><li></collection-id> </li></ul><ul><li><key column=“event_id”/> </li></ul><ul><li><many-to-many class=“Speaker” column=“speaker_id”/> </li></ul><ul><li></idbag> </li></ul>
  42. 42. idbags events events events event_attendees id bigint(pk) event_id bigint speaker_id bigint events events speakers id bigint(pk) event_speaker_id bigint (PK)
  43. 43. Lazy collections <ul><li>A lazy collection is populated on demand. It means that the collection of entity objects or values is populated only when the application accesses the collection. </li></ul><ul><li>Populating the collection happens transparently when the collection is first accessed. </li></ul><ul><li>Why lazy collections? </li></ul><ul><li>A collection of objects can possibly contain hundreds or thousands </li></ul><ul><li>of objects, and the application may not need to access the collection immediately, or at all. Loading hundreds of persistent objects for no reason will certainly impact application performance. It’s better to populate the persistent collection only when it is needed. </li></ul>
  44. 44. Lazy collections – Session closed problem <ul><li>To populate a lazy collection, the same Session instance used to retrieve the persistent object from the database must be open when the collection is populated. </li></ul><ul><li>The following code is incorrectly attempts to load the collection of </li></ul><ul><li>attendees for an Event after the Session has been closed: </li></ul><ul><li>Session session =factory.openSession(); </li></ul><ul><li>Event event = session.get(Event.class,eventId); </li></ul><ul><li>Session.close(); </li></ul><ul><li>Set attendees = event.getAttendees(); </li></ul>
  45. 45. Lazy collections – correct method <ul><li>Session session =factory.openSession(); </li></ul><ul><li>Event event = session.get(Event.class,eventId); </li></ul><ul><li>Set attendees = event.getAttendees(); </li></ul><ul><li>Session.close(); </li></ul><ul><li>Persistent collections are lazy by default in Hibernate 3. For non-lazy collections, you must explicitly declare them as lazy=“false” in the mapping definition. For example: </li></ul><ul><li><set name=“attendees” lazy=“false”> </li></ul><ul><li><key column=“event_id”/> </li></ul><ul><li><one-to-many class=“Attendee”/> </li></ul><ul><li></set> </li></ul>
  46. 46. Lazy collections – multitier problems <ul><li>Any collection, including collections of values and arrays, can be declared not to be “lazy’. </li></ul><ul><li>The problem with lazy collections in populating them in a multitier application, such as web application,where keeping the Session </li></ul><ul><li>open can be tricky. </li></ul><ul><li>Solution : The only requirement is that a Hibernate Session must </li></ul><ul><li>Be available in the view tier, which is possible when you use a servlet filter or spring to manage your Session instances. </li></ul>
  47. 47. Sorted Collections <ul><li>A common requirement when dealing with collection is to sort them </li></ul><ul><li>According to some criteria. The sorting criteria can be fixed or arbitrary, depending on application requirements. </li></ul><ul><li>Hibernate supports sorting sets,maps and bags. </li></ul><ul><li><set name=“attendees” order-by=“last_name”> </li></ul><ul><li><key column=“event_id”/> </li></ul><ul><li><one-to-many class=“Attendee”/> </li></ul><ul><li></set> </li></ul><ul><li>few more examples: </li></ul><ul><li>ordery-by = “last_name, first_name” </li></ul><ul><li>order_by = “last_name, first_name asc” </li></ul><ul><li>Use Filter to a collection </li></ul><ul><li>Set sortedAttendees = session.filter(event.getAttendees(), </li></ul><ul><li>“ order by this.phoneNumber”); </li></ul>
  48. 48. Filters <ul><li>Filters allow you to apply filtering criteria to returned objects at the Session level. You can pass parameters to filters, and they work with classes or collections. </li></ul><ul><li>To use filters, you first define them in the mapping files, and then enable a given filter by name when using the Session object. </li></ul><ul><li><hibernate-mapping> </li></ul><ul><li><filter-def name=“nameFilter”> </li></ul><ul><li><filter-param name=“nameFilterParam” type=“string”/> </li></ul><ul><li></fliter-def> </li></ul><ul><li></hibernate-mapping> </li></ul>
  49. 49. Filters - 2 <ul><li>With the filter defined, we can apply it to persistent classes and colections : </li></ul><ul><li><class name = “Event”> </li></ul><ul><li><filter name=“nameFilter” </li></ul><ul><li>condition = “:nameFilterParam=name”/> </li></ul><ul><li><set name=“attendees”> </li></ul><ul><li><filter name=“nameFilter” </li></ul><ul><li>condition = “:nameFilterParam = last_name”/> </li></ul><ul><li></set> </li></ul><ul><li></class> </li></ul>
  50. 50. Filters - 3 <ul><li>This code applies the filter to the name column in the events table, and to the last_name column in the attendees table. </li></ul><ul><li>To apply the filters, we must explicitly enable them at the Session level ; </li></ul><ul><li>Filter f = session.enablefilter(“nameFilter”); </li></ul><ul><li>f.setParameter(“nameFilterParam”, “Plenary”); </li></ul><ul><li>List results = session.createQuery(“from Event”).list(); </li></ul><ul><li>This code enables the named filter ant then sets the filter parameter. This results will only contain instances of Event with the name Plenary. </li></ul><ul><li>We can also enable multiple filters per session. </li></ul>
  51. 51. Metadata alternatives <ul><li>Attribute-oriented metadata </li></ul><ul><ul><li>JSR-175 annotations support, coming soon! </li></ul></ul><ul><ul><li>XDoclet Hibernate module </li></ul></ul><ul><li>Hibernate mapping metadata can be manipulated programmatically </li></ul><ul><ul><li>we can use dom4j or JDOM to generate mapping files in memory </li></ul></ul><ul><ul><li>we can manipulate the Hibernate Configuration metamodel directly </li></ul></ul><ul><ul><li>let's demonstrate this my adding a property to a mapped class… </li></ul></ul>/** * @hibernate.class * table=&quot;CATEGORY&quot; */ public class Category { ... /** * @hibernate.property */ public String getName() { return name; } ... }
  52. 52. Adding a property at runtime // Get the existing mapping for User from Configuration PersistentClass userMapping = cfg .getClassMapping(User.class); // Define a new column for the USER table Column column = new Column(); userMapping.getTable().addColumn(column); // Wrap the column in a Value SimpleValue value = new SimpleValue(); value.setTable( userMapping.getTable() ); value.addColumn(column); // Define a new property of the User class Property prop = new Property(); prop.setValue(value); prop.setName(&quot;motto&quot;); userMapping.addProperty(prop); // Build a new session factory, using the new mapping SessionFactory sf = cfg.buildSessionFactory();
  53. 53. Reading metadata at runtime <ul><li>There is also the runtime metamodel , exposed via the SessionFactory : </li></ul>Category category = ...; ClassMetadata meta = sessionFactory.getClassMetadata(Category.class); String[] metaPropertyNames = meta.getPropertyNames(); Object[] propertyValues = meta.getPropertyValues(category);