SlideShare une entreprise Scribd logo
1  sur  25
Professional Open Source™




         Transitive Persistence Filters




© JBoss, Inc. 2003, 2004.                                  07/17/04   1
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Professional Open Source™




         FILTERS




© JBoss, Inc. 2003, 2004.                               18
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
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
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
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
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
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
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

Contenu connexe

Similaire à 11 transitive persistence and filters

01 persistence and domain modeling
01 persistence and domain modeling01 persistence and domain modeling
01 persistence and domain modeling
thirumuru2012
 
12 hibernate int&cache
12  hibernate int&cache12  hibernate int&cache
12 hibernate int&cache
thirumuru2012
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 
Contexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformContexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platform
Bozhidar Bozhanov
 
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Anton Arhipov
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
Ranjan Kumar
 
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
JAXLondon2014
 

Similaire à 11 transitive persistence and filters (20)

14 hql
14 hql14 hql
14 hql
 
55j7
55j755j7
55j7
 
01 persistence and domain modeling
01 persistence and domain modeling01 persistence and domain modeling
01 persistence and domain modeling
 
12 hibernate int&cache
12  hibernate int&cache12  hibernate int&cache
12 hibernate int&cache
 
Hibernate
HibernateHibernate
Hibernate
 
05 inheritance
05 inheritance05 inheritance
05 inheritance
 
Arquillian in a nutshell
Arquillian in a nutshellArquillian in a nutshell
Arquillian in a nutshell
 
hibernate
hibernatehibernate
hibernate
 
OSGi & Java EE in GlassFish - Best of both worlds
OSGi & Java EE in GlassFish - Best of both worldsOSGi & Java EE in GlassFish - Best of both worlds
OSGi & Java EE in GlassFish - Best of both worlds
 
Arquillian in a nutshell
Arquillian in a nutshellArquillian in a nutshell
Arquillian in a nutshell
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
159747608 a-training-report-on
159747608 a-training-report-on159747608 a-training-report-on
159747608 a-training-report-on
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Contexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformContexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platform
 
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
 
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
 
OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010
OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010
OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010
 
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek PiotrowskiJDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
 
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
 

Plus de thirumuru2012

Plus de thirumuru2012 (7)

15 jpa
15 jpa15 jpa
15 jpa
 
15 jpa introduction
15 jpa introduction15 jpa introduction
15 jpa introduction
 
14 criteria api
14 criteria api14 criteria api
14 criteria api
 
09 transactions new1
09 transactions new109 transactions new1
09 transactions new1
 
09 transactions new
09 transactions new09 transactions new
09 transactions new
 
07 association of entities
07 association of entities07 association of entities
07 association of entities
 
15 jpaql
15 jpaql15 jpaql
15 jpaql
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Dernier (20)

Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

11 transitive persistence and filters

  • 1. Professional Open Source™ Transitive Persistence Filters © JBoss, Inc. 2003, 2004. 07/17/04 1
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Professional Open Source™ FILTERS © JBoss, Inc. 2003, 2004. 18
  • 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. 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. 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. 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. 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. 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. 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