Tag Archives: dpHibernate

Simpler Pre/Post Update wiring in Spring & dpHibernate using @Component

dpHibernate 2.0-RC1 was posted a few weeks back.

One of the features this offers is better “offical” support for Spring 2.5.x and Spring 3.0, through extension projects.

In doing this, dpHibernate is now significantly more extensible, by having all the various dependencies wired in at runtime, allowing developers to wire in their own components if required.

However, the current implementation is very verbose in the amount of boiler-plate wiring required to get dpHibernate up-and-running. This example illustrates my point nicely.

In the future, I plan on building out a much better support for sensible defaults in the Spring configuration.

Tonight I committed the first step in this on the 2.0 branch – adding support for auto-detecting pre/post update interceptors.

Now, all the wiring required for adding Pre/Post update interceptors is handled using Spring’s existing @Component interface. Eg:

Before:

       <bean id="objectChangeUpdater"
                class="org.dphibernate.persistence.state.AuthenticatedObjectChangeUpdater"
                scope="prototype">
                <property name="preProcessors" ref="dpHibernatePreProcessors" />
                <property name="postProcessors" ref="dpHibernatePostProcessors" />
        </bean>

        <!--  Used in update process, for resolving proxies back to the entity -->
        <bean id="hibernateProxyResolver" class="org.dphibernate.persistence.state.DbProxyResolver"
                scope="prototype">
                <constructor-arg ref="sessionFactory" />
        </bean>

        <!--  Optional.  Pre processors are invoked before an update operation.  Must implement IChangeMessageInterceptor -->
        <util:list id="dpHibernatePreProcessors">
                <ref bean="uniqueUsernameInterceptor" />
        </util:list>

        <!-- Optional.  Post processors are invokes after an update operation.  Must implement IChangeMessageInterceptor -->
        <util:list id="dpHibernatePostProcessors">
                <ref bean="passwordEncryptionInterceptor" />
        </util:list>
        <!-- An example of a customized message interceptor.
        CHecks to see if a username is unique in the database before performing an Create or Update on the ApplicationUser -->
        <bean id="uniqueUsernameInterceptor"
                class="com.mangofactory.pepper.service.interceptors.UsernameExistsChangeMessageInterceptor"
                autowire="constructor" />

After:

All the above XML is replaced by simply adding the @Component declaration to the top of your interceptors:

@Component
public class UsernameExistsChangeMessageInterceptor implements
        IPreUpdateInterceptor

…etc.

Notes:

  • You can still declare the interceptor beans themselves in the XML config if you prefer.  These will be detected along with any interceptors annotated with the @Component annotation.
  • You can override this behaviour by explicitly wiring in the preProcessors and postProcessors if you choose.  The autowired values are only used if the value has not been explicitly set.
  • In order to be eligible for autowiring, your interceptors must implement either IPreUpdateInterceptor or IPostUpdateInterceptor.  These are two new interfaces, both which subclass IChangeMessageInterceptor.  They don’t add any new methods, merely serve as a marker interface to indicate when in the lifecycle of the update they should be used.
  • For any of this to work, you need to be using the <context:component-scan  /> declaration in your spring context.  (See Section 3.12.2 in the spring docs here.
Tagged

Annotations in dpHibernate

dpHibernate now has support for annotations to provide fine grained control over how properties / objects are serialized when sending them to the client.

There’s 3 annotations available – I’ll discuss them here:

@NeverSerialize

This does pretty much what it says on the tin.  A property or class annotated with @NeverSerialize will never be serialized by dpHibernate when sending from Java -> Flex.

This is the server side equivilant of the [Transient] metatag in Flex.

For example:

public class ApplicationUser {

    private String password;

    @NeverSerialize
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

In this example, the password property is never serialized and sent to the client. Note – this doesn’t affect the deserialization behaviour when sending from Flex -> Java — which is handy when it comes to dealing with entity persistence.  You can set the Password property on the client and send it to the server and property updates are handled fine.  However, the value is never sent back to the client.

@AggressivelyProxy

The default behaviour and intent of dpHibernate is to handle lazily loaded properties from Hibernate.  This makes sending large collections of entities across to the client extremely efficient. However, sometimes you can have a situation where at serialization time, the collection / property has been fully hydrated by Hibernate – so there’s no lazy-loading going on.  In these situations, the default behaviour by dpHibernate is to send the full object (property / collection).  However, this can be expensive, and may not be neccessary.

@AggressivelyProxy tells the serializer to proxy the target, even if there’s no lazy-loading invovled.

For example, let’s consider an imaginary facebook clone, and the piece of code that handles populating the news feed for a given user.  The returned list of NewsFeedEntries is actually populated from various different feeds, and aggregated together. Eg:

NewsFeedService.java

    public NewsFeed getNewsFeed(ApplicationUser user)
    {
        NewsFeed newsFeed = new NewsFeed();
        newsFeed.addNewsFeedEntries(friendFeed.getTimelineEntries());
        newsFeed.addNewsFeedEntries(eventsFeed.getTimelineEntries());
        newsFeed.addNewsFeedEntries(myFeed.getTimelineEntries());
        return timeline;
    }

NewsFeed.java


public class NewsFeed {

    private List<NewsFeedEntry> newsFeedEntries;

    public void setNewsFeedEntries(List<NewsFeedEntry> timelineEntries) {
        this.newsFeedEntries = timelineEntries;
    }
    @AggressivelyProxy
    public List<NewsFeedEntry> getNewsFeedEntries() {
        return newsFeedEntries;
    }
    public void addNewsFeedEntries(List<NewsFeedEntry> entries)
    {
        newsFeedEntries.addAll(entries);
    }
}

Here, the newsFeedEntries is likely to have many many entities inside it.  However – given that it’s an aggregate of entities from other services, it’s probably not a lazy loaded collection from Hibernate.

The default dpHibernate behaviour is to serialize all the entities inside newsFeedEntries.  By adding the @AggressivelyProxy annotation, dpHibernate will proxy the collection, and the entities will be loaded from the cleint when they’re needed, giving a significant performance gain.

@EagerlySerialize

Overrides the default behaviour of the serializer, to always serializing the value (ie., never send a proxy).

The default behaviour of dpHibernate is to send a proxy for as many complex properties as it can, allowing the client to request the data as/when it’s needed.  This behaviour is often more efficient (minimizng the payload, and deserialization time on the client).

However, if the client is likely to always need a certain property, this can result in unnecessary trips being made to the server – adding unwanted latency.  By usiing the @EagerlySerialize annotation, dpHibernate will always send the real value of a property, and never a proxy in it’s place.

For example, continuing the example of the facebook clone discussed above – let’s assume that whenever we send a list of NewsFeedEntry objects to the client, that the client will always want to know the user the news feed item is about.

The default behaviour of dpHibernate is to proxy this property, which would result in an immediate second call to the server.  Instead, by annotating with @EagerlySerialize, the property is not proxied, and the real value is sent to the client:


public class NewsFeedEntry {

    private ApplicationUser entryUser;

    @EagerlySerialize
    public ApplicationUser getEntryUser() {
        return entryUser;
    }

    public void setEntryUser(ApplicationUser entryUser) {
        this.entryUser = entryUser;
    }

}

Tagged

Batch Loading Proxies in dpHibernate

I want to share a new feature of dpHibernate I’ve just committed to the codebase – batch loading.

The default behaviour of dpHibernate in the Flex Client is to lazy load any property that is required, as soon as it is first asked for.

This is all well and good, but in some cases, can generate a very high load on your webserver, and in turn – your database.

Take for example the following screenshot of an upcoming dpHibernate demo project:

For every question shown, there’s a list of associated tags.  This list is lazy loaded, so dpHibernate will fetch it as soon as it’s requested.  However, in the above screenshot, that generates a server request for each of the 21 displayed tags.  Hardly efficient.

dpHibernate now supports batching of requests for proxies.  It works as follows:

  • When a request is made to load a proxy from the flex client, dpHibernate postpones sending the request for a short time (the default is 50 milliseconds)
  • If another request is received during this delay, we extend the delay another 50 milliseconds, up to a maximum delay threshold (the default is 350 milliseconds)
  • Once either no more requests are made, or the maximum delay threshold is exceeded, send a request to load all the batches in a single server request.
  • On the server, make a single trip to the database to load all the entities
  • Return the loaded entites to the client

So, where previously this would’ve taken 21 server calls & 21 database trips, we’ve reduced it down to 1.  Not bad, eh?

Configuration

This option is disabled by default.

To enable it, set the operationBufferFactory property of the HibernateRemoteObject to an instance of a LoadDPProxyOperationBufferFactory.  (Terrible names, I know, but naming is hard.)  Here’s an example:

<?xml version="1.0" encoding="utf-8"?>
<fx:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:digitalprimates="http://www.digitalprimates.net/2007/mxml">
    <fx:Declarations>
        <digitalprimates:HibernateRemoteObject id="dataAccessService" destination="dataAccessService" operationBufferFactory="{bufferFactory}"  />
    </fx:Declarations>
    <fx:Script>
        <![CDATA[
            import net.digitalprimates.persistence.hibernate.rpc.LoadDPProxyOperationBufferFactory;
            [Bindable]
            public var bufferFactory:LoadDPProxyOperationBufferFactory = new LoadDPProxyOperationBufferFactory();
        ]]>
    </fx:Script>
</fx:Group>

On the server, you need something to handle the load requests.  This isn’t trivial, and historically we’ve left writing server side implementations up to individual projects.  However, there’s now a default DataAccessService which provides support for all dpHibernate features out-of-the-box.  I’ll write more about this later, but if you can’t wait, head over and grab the latest source, or browse the class directly.  (Note, there’s an implementation geared towards Spring environments too here).

Tagged

Entity Persistence with dpHibernate – Overview

dpHibernate is an open source project that facilitates lazy loading of hibernate entities with BlazeDS and Flex.

Note:  If you’re not familiar with the dpHibernate project, it may to have a read of this overview post

The topic discussed here is currently only available on the changeMessaging branch of dpHibernate.  The code is available here:

http://dphibernate.googlecode.com/svn/branches/changemessaging

Recently I committed some changes to a new branch of the source which now allows persistence operations (Create, Update, Delete) on entities, using a few lines of code.

Eg:

public class SomePM {
    public void doSomeWork(author:Author) {
        author.name = “Josh Bloch”;
        author.age = 30;
        author.publisher = publishers.findByName(“AddisonLee”);
        author.save();
    }
    public function createNewAuthor():void {
        var newAuthor : Author = new Author();
        newAuthor.name = “Sondhiem”;
        newAuthor.age = 55;
        newAuthor.save();
    }
    public function deleteAuthor(author:Author):void
    {
        author.deleteRecord();
    }
}

This is similar to the entity persistence provided by LCDS, but without the exorbitant licensing fee!

The save() and deleteRecord() methods are made available through the new IUpdatableHibernateProxy interface. Generally, these would delegate work back to the HibernateUpdater class. Examples of this implementation are shown later.

This approach saves the process of having to write individual update services for each entity (which, often requires several methods for each field. Painful!)

Eg:

// Actionscript:
[Managed]
public class Author extends BaseEntity {
    public var id : int;
    public var name : String;
    public var age : int;
}
public class BaseEntity extends HibernateBean {
    public function save(responder:IResponder = null) : AsyncToken
    {
        return HibernateUpdater.save(this,responder);
    }
    public function deleteRecord(responder:IResponder=null) : AsyncToken
    {
        return HibernateUpdater.deleteRecord(this);
    }
}

From this, Author, and all other subclasses of BaseEntity inherit a save method (which handles both creates and updates of entities) and delete method.

Note, that should you wish to keep persistence methods out of your entity classes, the following is also valid:

[Managed]
public class Author implements IHibernateProxy {
    public var id : int;
    public var name : String;
    public var age : int;
    // IHibernateProxy impl. Excluded...
}

public class SomePM {
    public function updateAuthor(author:Author):void
    {
        HibernateUpdater.update(author);
    }
    // Or, for that matter...
    public function updateAnyEntity(entity:IHibernateProxy):void
    {
        HibernateUpdater.update(entity);
    }
}

Or, if you prefer a more dependency injection friendly implementation:

public class SomePM {
    [Inject] // Actual injection depends on your DI framework of choice.
    public var hibernateUpdater:IHibernateUpdater;

    public function updateAuthor(author:Author):void
    {
        hibernateUpdater.update(author);
    }
}

(Note, this would also work within the Author class itself, should you prefer)

The possibilities for implementation are pretty open, and not overly prescriptive from the dpHibernate framework. The only requirements in terms of your entity classes to facilitate persistence are that they are tagged [Managed] (or implement IManaged), and implement IHibernateProxy.

Nested properties and collections

Both nested properties and changes to collections are supported.

Eg:

Nested properties

public class SomePM {
    public function doSomeWork(book:Book):void
    {
        book.author.name=”newName”;
        book.save();
    }
}

Collections

public class SomePM {
    public function doSomeWork(author:Author,book:Book):void
    {
        author.books.addItem(book);
        author.save();
    }
}

A combination of both

public class SomePM {
    public function doSomeWork(author:Author,book:Book):void
    {
        author.books.addItem(book);
        book.title=”This is the new title”;
        author.save(); // Also persists the change to book.title,
        // as it's part of the author.books collection.
    }
}

Efficient .save()’s

When calling save() on an entity, the actual entity itself is not passed across to the update service. For complex entity trees with collections and nested hierarchies, serialization within the Flash player can be painfully slow.

Eg, consider the following common example:

[Managed]
public class Author extends BaseEntity {
    public var id : int;
    public var name : String;
    public var age : int;
    public var books : ArrayCollection;
}
[Managed]
public class Book extends BaseEntity {
    public var title : String;
    public var author : Author;
}

The Parent entity – Author, contains a list of children entities – books, each of which contains a reference back to it’s parent. These circular references are commonplace, and required in many scenarios by Hibernate.

If we were to use standard AMF serialization for this, the nested tree can get very deep very quickly, depending on the number of Books an Author has written. Additionally, this cost is completely unnecessary if the only thing changed on the Author is it’s name.

Also, given that dpHibernate facilitates lazy loading, it’s quite possible that the property Author.books hasn’t even been populated yet at the time of serialization. Standard AMF serialization would trigger this loading unnecessarily.

Instead, only a list of changes that have occurred to the entity are passed along. This keeps the serialization process light, and quick. Nested properties & collections are handled, and circular references like the one described above are handled efficiently, ensuring that each entity is processed only once.

Essentially, instead of sending through the entire updated entity, dpHibernate sends a collection of changes through to be processed by the server – i.e. :

  • Author record 123 : name changed from “Josh bloch” to “Josh Bloch”
  • Author record 123 : books collection now contains :
    • Book record 123
    • Book record 456
    • A new book record, tentatively identified as ABC
  • Book record 456 : title changed from “effective .net” to “Effective Java”
  • Book record ABC created.

These records are simple objects of primitive types, so serialize very quickly. Once on the server, they are ordered to ensure that dependencies are processed in the appropriate order. Ie, The change record for the creation of Book ABC is processed before it is added to the books collection of Author 123.

Considerations

The entity persistence code of dpHibernate is still new, so typical warnings about bugs apply. That said, dpHibernate is currently being used successfully within a large scale commercial project.

Also, currently these changes to dpHibernate require that your project is using Spring on the Java tier. This dependency will be removed shortly, however for this reason, the entity persistence code is kept separate from the core dpHibernate trunk.

Finally, there are performance implications which you must be careful of. However, these can be easily mitigated through use of new custom metatags, and avoiding state tracking on all entities by default. Fine tuning dpHibernate for performance is discussed in a later blog post.

Tagged

Implementing Paged Collections in dpHibernate

A colleague posted an interesting question regarding lazy loading, and I realized that it’s something that we could be doing better in dpHibernate.

Note:  If you’re not familiar with the dpHibernate project, it may to have a read of this overview post

The topic discussed here is currently only available on the changeMessaging branch of dpHibernate.  The code is available here:

http://dphibernate.googlecode.com/svn/branches/changemessaging

Overview of data paging in flex

The process of paging data is used where a large collection of information is returned to the client.  Instead of sending the entire collection (which can be expensive in terms of broadband and client processing time), data is paged across.

When a paginated collection is returned to flex, normally an ArrayCollection arrives at the client with the first n items populated, and proxies in place for the remainder of the collection.  By sending proxies in place of the actual collection members, the length of the array collection is still reported correctly, meaning that view components (such as the list & datagrid etc) display scroll bars correctly.

When a call is made to getItemAt() on an ArrayCollection that references a proxied (not yet loaded) item, the following occurs:

  • Trigger a load to a remote service to load the requested item asynchronously
  • Throw an ItemPendingError
  • When the load request completes, replace the proxy in the array collection at the requested index with the newly loaded item.

View components in the flex framework are smart enough to only request the items that need to be displayed.

If a collection of 1000 items is returned to the client and displayed in a list component which is high enough to display 10 items, the first 10 will be retrieved.  As the user scrolls around in the List component, items are loaded non-sequentially as required.  Eg.,  If a user scrolls down to the 200th item, items 200 – 210 are loaded, though items 11 – 199 are skipped, as these are not required to be displayed.

dpHibernate

Previously, dpHibernate had lazy loading of collections, but no support for paging large collections.

If an entity declares a property whose value is a collection, and the value has not yet been loaded from the database at serialization time, it’s sent to the flex client as a collection of uninitialized dpHibernate proxies. This allows that on the flex client when looking at the collection for the first time, the length is reported correctly, even though none of the data has yet been loaded.

When the flex client accesses the property, currently the entire collection is loaded. This works fine for a collection with 10 items, but causes big problems if there’s 1000.

What would be better is to page the data down in the same way that LCDS does it – ie, return the proxies, but only load the members required to show on screen.

Implementation

Let’s step through how this works.

First of all, you need to enable paging. The new paging of collections in dpHibernate is disabled by default. To turn it on, set a page size in the hibernateSerializer bean in the spring config, as follows:

<bean id="hibernateSerializerBean"
class="net.digitalprimates.persistence.translators.hibernate.HibernateSerializer" scope="prototype">
    <property name="pageSize" value="3"/>
</bean>

When a collection is being serialized with paging enabled, the returned collection contains a mixture of the real instances of the collections members, and special lightweight proxies to the remainder of the collections members.

These proxies are instances of the entity class, but with none of it’s properties populated except for the proxyKey, and proxyInitialized set to false.

ArrayCollection and IList

ArrayCollections are one of the few instances of composition within the flex framework. ArrayColellections work by managing an internal IList which contians it’s members. By default, this is an instance of an ArrayList, however we can modify the behaviour by passing in a different implementation – in our case, one that facilitates lazy loading.

ArrayCollection’s methods such as getItemAt() (which is used by the DataGrid, and other components typically associated with lazy loading) are delegated down to the internal IList method. It’s here that the framework expects us to throw the ItemPendingError if the item we’re after isn’t held locally.

In order to get our lazy loading going, we need to augment the behaviour of this list to detect our proxy objects, load the item, and throw the ItemPendingError. DpHibernate uses a class called ManagedArrayList to facilitate this.

When the results of a remote call are returned, they’re examined to see if there’s an array collection there, and – if so – if that array collection has been paged. In that case, we swap out the default ArrayList with an instance of the ManagedArrayList:

private static function manageArrayCollection(collection:ArrayCollection,ro:IHibernateRPC):void
{
    // Trimmed..
    if (isPagedCollection)
    {
        var managedArrayList:ManagedArrayList = new ManagedArrayList(collection.source);
        collection.list = managedArrayList;
    }
}

Now, inside our ManagedArrayList, we need to detect requests for proxied data:

override public function getItemAt(index:int, prefetch:int=0) : Object
{
    var result : Object = super.getItemAt(index,prefetch);
    if (result is IHibernateProxy && IHibernateProxy(result).proxyInitialized == false)
    {
        handleRemoteItem(IHibernateProxy(result),index,prefetch);
    }
    return result;
}
private function handleRemoteItem(proxy:IHibernateProxy,index:int,prefetch:int):void
{
    var remoteService : IHibernateRPC = HibernateManaged.getIHibernateRPCForBean( proxy );
    var token : AsyncToken = remoteService.loadProxy(proxy.proxyKey,proxy);
    token.addResponder(new Responder(onPendingItemLoaded,onFault));
    var itemPendingError : ItemPendingError = new ItemPendingError("Item is pending");
    var pendingItem:PendingItem = new PendingItem(itemPendingError,index);
    pendingItems[token] = pendingItem;
    throw itemPendingError;
}

When a call is made to getItemAt(), we check to see if it’s an uninitialised IHibernateProxy instance. If so, control is passed off to handleRemoteItem().

Loading data from the server

dpHibernate uses an extension of the RemoteObject class called HibernateRemoteObject.  Objects which arrive on the client as the result of a call to a method on a HibernateRemoteObjectA get “managed”.  Among the tasks performed when “managing” an object, dpHibernate stores a reference to the HibernateRemoteObject instance from which the remote object arrived.  This allows us to get a reference back to the server from the remote object.

A reference to this HibernateRemoteObject is retrieved by calling:

var remoteService : IHibernateRPC = HibernateManaged.getIHibernateRPCForBean( proxy );

Using this reference, a call is issued to the server to load the real value of the proxy, and an ItemPendingError is thrown.

ItemPendingError

The ItemPendingError is not a dpHibernate specific concept – instead, it’s provided by the flex framework for classes to provide support for paginated & remote data.  Some flex framework components already provide support for the ItemPendingError out of the box – such as the List control and the Datagrid control.

You’ll notice that the thrown error is stored along with other details of the call. This is because other classes which catch the ItemPendingError can assign IResponder(s) to get notified when the item has been loaded. By storing the error, we keep reference to this list of responders, and can invoke them accordingly:

private function onPendingItemLoaded(data:Object):void
{
    var resultEvent:ResultEvent = ResultEvent(data);
    var token:AsyncToken = resultEvent.token;
    var pendingItem : PendingItem = pendingItems[token];
    var result:Object = resultEvent.result;
    this.setItemAt(result,pendingItem.index);
    for each ( var responder : IResponder in pendingItem.error.responders )
    {
        responder.result(data);
    }
    delete pendingItems[token]
}

When the item is loaded from the server, the proxy in the list is replaced at the appropriate index. Then, all other responders are invoked so they can take any action necessary.

Tagged

DpHibernate – An Overview

I’m going to start posting a series of articles that discuss some of the work I’ve been doing recently on dpHibernate.

I’m order to prevent repeating the basics of how dpHibernate works in each blog, here’s a little primer on the subject.

Project

dpHibernate is a BlazeDS adapter to provide support for Hibernate entities in actionscript. It’s open source, and the code is available from http://dphibernate.googlecode.com.  Many of the topics discussed on this blog specifically target the “changeMessaging” branch, which at the time of writing has not been merged back into the trunk.  The branch is available for checking out here:

http://dphibernate.googlecode.com/svn/branches/changemessaging

Lazy Loading

dpHibernate’s initial goal was to provide an adapter which handles serialization of a Hibernate object effectively. Eg: Imagine the following structure:

[Managed]
public class Author extends BaseEntity {
    public var id : int;
    public var name : String;
    public var age : int;
    public var publisher : Publisher;
    public var books : ArrayCollection;
}
[Managed]
public class Book extends BaseEntity {
    public var title : String;
    public var author : Author;
}
[Managed]
public class Publisher extends BaseEntity
{
    public var authors : ArrayCollection;
    public var books : ArrayCollection;
}

If a service is written returning a Book object from hibernate to the flex client, it’s possible that a LazyLoading exception is thrown when serializing the author property. This is because the entity is lazily loaded, and has not yet been retrieved from the database.

While one possible solution here is to load the author during serialization, this also requires loading the Author.publisher property, and the Author.books() collection, which in turn will load many more books etc. This approach can quickly becomes too expensive and bandwidth-heavy to use in a real world scenario.

Facilitating Lazy Loading with the IHibernateProxy

Instead of serializing these entities, dpHibernate sends down a proxy in their place. If and when the flex client accesses the property represented by the proxy, then that entity is retrieved from the server. Again, only the primitive values of the returned entity are serialized and sent across to the flex client. Ie., when reading Book.author() for the first time, the Author object is retrieved from the server, however it’s publisher property is represented by a proxy until such time as it is required.

Similarly, the property Author.books() is sent as a collection of proxies until such time as they are accessed. Note that because a proxy exists for every entity within the collection, attributes such as the length of the collection are still reported correctly.

In order to facilitate this lazy loading, all entity classes are required to either subclass HibernateBean, or implement IHIbernateProxy, which declares two properties:

public interface IHibernateProxy
{
    function get proxyKey():Object;
    function set proxyKey( value:Object ):void;

    function get proxyInitialized():Boolean;
    function set proxyInitialized( value:Boolean ):void;
}

Normally, the developer doesn’t access or modify these properties directly – instead they are there to facilitate the lazy loading process.

Specifics of how the lazy loading works are beyond the scope of this tutorial, but will be discussed in a later blog post.

Entity Persistence

dpHibernate provides functionality for persisting entities without having to write update services for each entity, through a simple save() method of the IUpdateableHibernateProxy interface:

public interface IUpdatableHibernateProxy extends IHibernateProxy
{
    function save(responder:IResponder=null) : AsyncToken;
    function deleteRecord(responder:IResponder=null) : AsyncToken;
}

dpHibernate provides support for creating, deleting and updating entities, including support for nested entities and collections.

Eg:

public class SomePM {
    public function doSomeWork(book:Book):void
    {
        book.author.name=”newName”;
        book.save();
    }
}

The entity persistence features are discussed in detail in an upcoming blog.

Further reading

That’s the broad overview of dpHibernate.

Other, more detailed blogs cover off:

Tagged

BlazeDS, Enums, and a comedy of very small errors

For the past two nights while working on my side project, I’ve been banging my head against the wall trying to pass Enums back and forth across BlazeDS to my Flex Client.

I know it’s possible, after all, I’ve seen it on the internet….

However, depsite what ol’ man google said, I was getting errors when sending the enums back from Flex to my server (though they went fine the other way).

In addition to the standard Flex / BlazeDS stack, I’ve been using two very handy open source tools :

  • dpHibernate to assist with serialization of Hibernate Lazy proxies
  • DTO2FX for some really funky AS class generation

Turns out that very small bugs inside each of these were to blame.  I post here in case — through some odd twist of fate —  you, dear reader, have the same stack:

dpHibernate

dpHibernate was attempting to deserialize Enum classes as a hibernate proxy.  Adding a test for Enum inside the isSimple method of the HibernateSerializer took care of that:


    private boolean isSimple(Object obj)
    {
        return ((obj == null)
                || (obj instanceof String)
                || (obj instanceof Character)
                || (obj instanceof Boolean)
                || (obj instanceof Number)
                || (obj instanceof Date)
                || (obj instanceof Calendar)
                || (obj instanceof Document))
                || (obj instanceof Enum);
    }

DTO2FX

DTO2FX uses an (IMHO) overly complicated template for their generated Enums.  Rather than just use the method discussed here, which allows for a simple enum client side class, they use a much more complex template.  It requires the use of a custom Serializer / Deserializer within Blaze.

Here, I thought of a few approaches:

Change the template used by DTO2FX and recompile my custom version

This requires downloading no less than 5 seperate open source projects from CVS (who the hell uses CVS anymore?) and working out what was going on.  I have previously given up on changing DTO2FX as a simple task, so didn’t even bother this time.

Don’t use DTO2FX to generate the Enums — do it by hand

I’m not using a large number of Enums in my project, and I can live with hand coding them.  However, one of the wonderful features of DTO2FX, is that it uses compile time checking of your Java project to ensure that every dependent type has been generated.  If you miss a type out (even intentionally), you get an error at compile time.  Sadly, there’s no way to turn this behaviour off — which meant I had to consider:

Stop using DTO2FX completely

I seriosuly considered this.  I love DTO2FX because it’s quick to use, maintains my classes in the background, and uses the Generation Gap pattern, meaning that in my generated classes I can still put custom code.  However, this is not the first time that I’ve ground to a halt because of some quirk in the way that DTO2FX generates it’s code.

Also, I find that having to make an architectural decision on my project because a tool won’t generate code in a specific way is unacceptable.  If it wasn’t so good in other ways, I’d have ditched it.

I googled for an appropriate replacement for DTO2FX, but couldn’t find one.  Which left me with….

Make DTO2FX’s Enums work.

Although the fix is simple, the debugging and locating the fault was the hard part.

In the end, all it took was adding this override to EnumPropertyProxy :

    public Object createInstance(String className)
    {
        Class cl = AbstractProxy.getClassFromClassName(className);

        if (cl.isEnum())
        {
            return new EnumHolder(cl);
        }
        else
            throw new IllegalArgumentException("**** samples.EnumProxy registered for a class which is not an enum: " + cl.getName());
    }

And from there, (after I reverted all my other hackery) it worked.

Cheers

Marty

Tagged ,