+ All Categories
Home > Technology > 11 transitive persistence and filters

11 transitive persistence and filters

Date post: 16-Dec-2014
Category:
Upload: thirumuru2012
View: 370 times
Download: 2 times
Share this document with a friend
Description:
 
Popular Tags:
25
Professional Open Source™ © JBoss, Inc. 2003, 2004. 1 07/17/04 Transitive Persistence Filters
Transcript
Page 1: 11 transitive persistence and filters

Professional Open Source™

© JBoss, Inc. 2003, 2004. 1

07/17/04

Transitive Persistence Filters

Page 2: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 2

Professional Open Source™

Transitive Persistence

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.

Page 3: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 3

Professional Open Source™

Persistence by reachability

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.

Page 4: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 4

Professional Open Source™

Problem with persistence by reachability

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

Page 5: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 5

Professional Open Source™

Applying cascading to associations

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.

Page 6: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 6

Professional Open Source™

Association cascade styles

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.

Page 7: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 7

Professional Open Source™

Association cascade styles

Let’s enable transitive persistence for the Category hierarchy:

Usually, we apply cascade only for to-many associations.

Note that cascade is a recursive notion!

<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>

Page 8: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 8

Professional Open Source™

Examples

Do we need to persist the newly added laptops separately ??See the mapping from the previous page

Page 9: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 9

Professional Open Source™

Example

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.

Page 10: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 10

Professional Open Source™

Automatic save or update for detached object graphs

If we don’t know if something is detached or transient:

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.

Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();

// Let Hibernate decide whats new and whats detachedsession.saveOrUpdate(theRootObjectOfGraph);

tx.commit();session.close();

Page 11: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 11

Professional Open Source™

Detecting transient instances

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>

Page 12: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 12

Professional Open Source™

Transitive deletion

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.

Page 13: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 13

Professional Open Source™

Delete-orphan

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.

Page 14: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 14

Professional Open Source™

Processing bulk updates with batches

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, youopen 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 persistencecontext before loading the next 100 objects into it.

Page 15: 11 transitive persistence and filters

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

Page 16: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 16

Professional Open Source™

Using a stateless Session

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.

Page 17: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 17

Professional Open Source™

Using a stateless Session

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

Page 18: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 18

Professional Open Source™

FILTERS

Page 19: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 19

Professional Open Source™

Defining a data filter

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>

Page 20: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 20

Professional Open Source™

Applying and implementing the filter

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.

Page 21: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 21

Professional Open Source™

Enabling the filter

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();

Page 22: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 22

Professional Open Source™

Exceptional cases for filters

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.

Page 23: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 23

Professional Open Source™

Filtering collections

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.

Page 24: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 24

Professional Open Source™

Filtering <one-to-many> collections

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 ofitems of a Category is filtered.

Page 25: 11 transitive persistence and filters

© JBoss, Inc. 2003, 2004. 25

Professional Open Source™

A Filter that applies to many entities

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.


Recommended