Skip to content

how to add serialized properties

yigit edited this page Aug 21, 2012 · 1 revision

Assume you have entity Movie and an inner class in your codebase Movie.Cast which implements serializeable.

There is a one to many relationship between Movie and Cast.

Then you can add it to your entity as follows:

movie.addSerializedProperty("casts", "List<Cast>", "List<Cast>").addImport("java.util.List")
    .addImport(schema.getDefaultJavaPackage() + "." + "Movie.Cast");

This will create two fields inside MovieBase class; private byte[] __casts and private List<Cast> casts. Unlike other properties which are protected, these are private to control serialization flow.

It will also generate following getter and setter:

public List<Cast> getCasts() {
    if(casts == null && __casts != null) {
       casts  = (List<Cast>) DbUtils.deserializeObject(__casts);
       __casts = null; //clear memory, before save, we'll re-serialize anyways if needed
    }
    return casts;
}

public void setCasts(List<Cast> casts) {
    this.casts = casts;
    __casts = null; //onBeforeSave will do serialization
}

Another hook in our custom implementation calls public void onBeforeSave() { on entity classes before they are saved to database. Inside that method, the following code exists:

if(__casts == null) {
    __casts = DbUtils.serializeObject(casts);
}

DbUtils.serializeObject just serializes given object into a byte array.

There is an obvious unnecessary re-serialization when saving the object but since we don't have any idea about the object, we cannot check if it is changed when read. Of course we could force caller to make an invalidate call or use some getWritable method but it would make the rest of the code ugly.

My further plan is to have something special for lists and return un-modifiable list.

Clone this wiki locally