Professional Open Source™         Transitive Persistence Filters© JBoss, Inc. 2003, 2004.                                 ...
Transitive Persistence                                                           Professional Open Source™  Transitive pe...
Persistence by reachability                                                           Professional Open Source™  An objec...
Problem with persistence by reachability                                                             Professional Open Sou...
Applying cascading to associations                                                           Professional Open Source™  I...
Association cascade styles                                                                     Professional Open Source™ ...
Association cascade styles                                                                                  Professional O...
Examples                                                        Professional Open Source™    Do we need to persist the new...
Example                                                                                Professional Open Source™         H...
Automatic save or update for detached object graphs                                                                       ...
Detecting transient instances                                                                                  Professiona...
Transitive deletion                                                               Professional Open Source™  Imagine that...
Delete-orphan                                                           Professional Open Source™  In certain situations,...
Processing bulk updates with batches                                                                          Professional...
Professional Open Source™  For best performance, you should set the size of the Hibernate (and   JDBC) configuration prop...
Using a stateless Session                                                                           Professional Open Sour...
Using a stateless Session                                                             Professional Open Source™  You no l...
Professional Open Source™         FILTERS© JBoss, Inc. 2003, 2004.                               18
Defining a data filter                                                                      Professional Open Source™  A ...
Applying and implementing the filter                                                                        Professional O...
Enabling the filter                                                                 Professional Open Source™  We defined...
Exceptional cases for filters                                                                Professional Open Source™  R...
Filtering collections                                                                        Professional Open Source™  C...
Filtering <one-to-many> collections                                                                          Professional ...
A Filter that applies to many entities                                                                          Profession...
Upcoming SlideShare
Loading in …5
×

11 transitive persistence and filters

574 views
505 views

Published on

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
574
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

11 transitive persistence and filters

  1. 1. Professional Open Source™ Transitive Persistence Filters© JBoss, Inc. 2003, 2004. 07/17/04 1
  2. 2. Transitive Persistence Professional Open Source™  Transitive persistence is a technique that allows you to propagate  persistence to transient and detached subgraphs automatically.  For example, if you add a newly instantiated Category to the already persistent hierarchy of categories, it should become automatically persistent without a call to save() or persist().  There is more than one model for transitive persistence. The best known is persistence by reachability.© JBoss, Inc. 2003, 2004. 2
  3. 3. Persistence by reachability Professional Open Source™  An object persistence layer is said to implement persistence by reachability if any instance becomes persistent whenever the application creates an object reference to the instance from another instance that is already persistent.© JBoss, Inc. 2003, 2004. 3
  4. 4. Problem with persistence by reachability Professional Open Source™  With Persistence by reachability, hibernate can make all the transient or detached instances which are reachable through a persistent instance . But the other way is not possible . i.e, an instance cannot become transient and be deleted from the database if it isn’t reachable via references from the root persistent object.  So, persistence by reachability is at best a halfway solution. It helps you make transient objects persistent and propagate their state to the database without many calls to the persistence manager.  It isn’t a full solution to the problem of making persistent objects transient (removing their state from the database). You can’t remove all reachable instances when you remove an object—other persistent instances may still hold references to them© JBoss, Inc. 2003, 2004. 4
  5. 5. Applying cascading to associations Professional Open Source™  If, for a particular association, you wish to enable transitive persistence, you must override this default in the mapping metadata. These settings are called cascading options.  In XML mapping metadata, you put the cascade="..." attribute on  <one-to-one> or <many-to-one> mapping element to enable transitive state changes. All collections mappings (<set>, <bag>, <list>, and <map>) support the cascade attribute. The delete-orphan setting, however, is applicable only to collections.© JBoss, Inc. 2003, 2004. 5
  6. 6. Association cascade styles Professional Open Source™  Hibernate supports more flexible cascading options for associations: – none: Hibernate ignores the association – save-update: Hibernate saves new and updates detached instances – delete: Hibernate deletes associated instances – all: save-update and delete – lock : cascades the lock() operation to associated instances, reattaching  them to the persistence context if the objects are detached. – delete-orphans Hibernate will delete dereferenced instances  Cascading options can be declared on an association-basis.  This model is more flexible but more complex model than persistence by reachability.© JBoss, Inc. 2003, 2004. 6
  7. 7. Association cascade styles Professional Open Source™  Let’s enable transitive persistence for the Category hierarchy: <class name=“Category” … > … <many-to-one name=“parentCategory” column=“PARENT_ID” cascade=“none” /> <set name=“childCategories” cascade=“save-update” > <key column=“PARENT_ID”/> <one-to-many class=“Category”/> </set> </class> Usually, we apply cascade only for to-many associations. Note that cascade is a recursive notion!© JBoss, Inc. 2003, 2004. 7
  8. 8. Examples Professional Open Source™ Do we need to persist the newly added laptops separately ?? See the mapping from the previous page© JBoss, Inc. 2003, 2004. 8
  9. 9. Example Professional Open Source™ Hibernate inspects the database identifier property of the laptops.parentCategory object and correctly creates the reference to the Computer category in the database. Hibernate inserts the identifier value of the parent into the foreign key field of the new Laptops row in CATEGORY. Because you have cascade="none" defined for the parentCategory association, Hibernate ignores changes to any of the other categories in the hierarchy (Computer, Electronics)! It doesn’t cascade the call to save() to entities referred by this association.© JBoss, Inc. 2003, 2004. 9
  10. 10. Automatic save or update for detached object graphs Professional Open Source™  If we don’t know if something is detached or transient: Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); // Let Hibernate decide whats new and whats detached session.saveOrUpdate(theRootObjectOfGraph); tx.commit(); session.close(); Hibernate will walk the graph, starting at the “root” object passed to saveOrUpdate(), navigating to all associated entities where the association is declared cascade="save-update“. Hibernate will decide if each object in the graph needs to be inserted or updated.© JBoss, Inc. 2003, 2004. 10
  11. 11. Detecting transient instances Professional Open Source™  Hibernate will assume that an instance is transient if – the identifier property is null – the version or timestamp property (if there is one) is null – the unsaved-value for the identifier property defined in the mapping matches – the unsaved-value for the version or timestamp property defined in the mapping matches – you implement your own strategy with an Interceptor <class name="Category" table="CATEGORY"> <!-- null is the default, 0 is for primitive types --> <id name="id" unsaved-value="0"> <generator class="native"/> </id> .... </class>© JBoss, Inc. 2003, 2004. 11
  12. 12. Transitive deletion Professional Open Source™  Imagine that you want to delete a Category object. You have to pass this object to the delete() method on a Session; it’s now in removed state and will be gone from the database when the persistence context is flushed and committed. However, you’ll get a foreign key constraint violation if any other Category holds a reference to the deleted row at that time  It’s your responsibility to delete all links to a Category before you delete the instance.© JBoss, Inc. 2003, 2004. 12
  13. 13. Delete-orphan Professional Open Source™  In certain situations, you want to delete an entity instance by removing a reference from a collection. In other words, you can guarantee that once you remove the reference to this entity from the collection, no other reference will exist. Therefore, Hibernate can delete the entity safely after you’ve removed that single last reference. Hibernate assumes that an orphaned entity with no references should be deleted.© JBoss, Inc. 2003, 2004. 13
  14. 14. Processing bulk updates with batches Professional Open Source™ You use an HQL query (a simple one) to load all Item objects from the database. But instead of retrieving the result of the query completely into memory, you open an online cursor. A cursor is a pointer to a result set that stays in the database. You can control the cursor with the ScrollableResults object and move it along the result. To avoid memory exhaustion, you flush() and clear() the persistence context before loading the next 100 objects into it.© JBoss, Inc. 2003, 2004. 14
  15. 15. Professional Open Source™  For best performance, you should set the size of the Hibernate (and JDBC) configuration property hibernate.jdbc.batch_size to the same size as your procedure batch: 100. All UDPATE statements that are executed during flushing are then also batched at the JDBC level.© JBoss, Inc. 2003, 2004. 15
  16. 16. Using a stateless Session Professional Open Source™  Without a persistence context, you wouldn’t be able to manipulate  object state and have Hibernate detect your changes automatically.  If u want to do bulk operations and don’t want the benefit of persistence context, u can use org.hibernate.StatelessSession .  This statement-oriented interface, org.hibernate.StatelessSession, feels and works like plain JDBC, except that you get the benefit from mapped persistent classes and Hibernate’s database portability.© JBoss, Inc. 2003, 2004. 16
  17. 17. Using a stateless Session Professional Open Source™  You no longer work with objects in persistent state; everything that is returned from the database is in detached state. Hence, after modifying an Item object, you need to call update() to make your changes permanent.  A StatelessSession doesn’t have a persistence context cache and doesn’t interact with any other second-level or query cache. Everything you do results in immediate SQL operations.  No Dirty Checking  No Cascading  No Guaranteed scope of Identity© JBoss, Inc. 2003, 2004. 17
  18. 18. Professional Open Source™ FILTERS© JBoss, Inc. 2003, 2004. 18
  19. 19. Defining a data filter Professional Open Source™  A dynamic data filter is defined with a global unique name, in mapping metadata. You can add this global filter definition in any XML mapping file you like, as long as it’s inside a <hibernate-mapping> element: <filter-def name="limitItemsByUserRank"> <filter-param name="currentUserRank" type="int"/> </filter-def>© JBoss, Inc. 2003, 2004. 19
  20. 20. Applying and implementing the filter Professional Open Source™  You want to apply the defined filter on the Item class so that no items are visible if the logged-in user doesn’t have the necessary rank: The <filter> element can be set for a class mapping. It applies a named filter to instances of that class. The condition is an SQL expression that’s passed through directly to the database system, so you can use any SQL operator or function. It must evaluate to true if a record should pass the filter. Unqualified columns, such as SELLER_ID, refer to the table to which the entity class is mapped. If the currently logged-in user’s rank isn’t greater than or equal than the rank returned by the subquery, the Item instance is filtered out.© JBoss, Inc. 2003, 2004. 20
  21. 21. Enabling the filter Professional Open Source™  We defined a data filter and applied it to a persistent class. It’s still not filtering anything; it must be enabled and parameterized in the application for a particular Session.  Filter filter = session.enableFilter("limitItemsByUserRank");  filter.setParameter("currentUserRank", loggedInUser.getRanking());  You enable the filter by name; this method returns a Filter instance. This object accepts the runtime arguments. You must set the parameters you have defined.  Now every HQL or Criteria query that is executed on the filtered Session restricts the returned Item instances:  List<Item> filteredItems = session.createQuery("from Item").list();  List<Item> filteredItems = session.createCriteria(Item.class).list();© JBoss, Inc. 2003, 2004. 21
  22. 22. Exceptional cases for filters Professional Open Source™  Retrieval by identifier can’t be restricted with a dynamic data filter.  many-to-one or one-to-one associations are also not filtered .  If a many-to-one association was filtered (for example, by returning null if you call anItem.getSeller()), the multiplicity of the association would change! This is also conceptually wrong and not the intent of filters.© JBoss, Inc. 2003, 2004. 22
  23. 23. Filtering collections Professional Open Source™  Calling aCategory.getItems() returns all Item instances that are referenced by that Category. This can be restricted with a filter applied to a collection: In this example, you don’t apply the filter to the collection element but to the <many-to-many>. Now the unqualified SELLER_ID column in the subquery references the target of the association, the ITEM table, not the CATEGORY_ITEM join table of the association.© JBoss, Inc. 2003, 2004. 23
  24. 24. Filtering <one-to-many> collections Professional Open Source™  If the association between Category and Item was one-to-many, you’d created the following mapping: If you now enable the filter in a Session, all iteration through a collection of items of a Category is filtered.© JBoss, Inc. 2003, 2004. 24
  25. 25. A Filter that applies to many entities Professional Open Source™  If you have a default filter condition that applies to many entities, declare it with your filter definition: <filter-def name="limitByRegion“ condition="REGION >= :showRegion"> <filter-param name="showRegion" type="int"/> </filter-def>  If applied to an entity or collection with or without an additional condition and enabled in a Session, this filter always compares the REGION column of the entity table with the runtime showRegion argument.© JBoss, Inc. 2003, 2004. 25

×