Skip to content
rnentjes edited this page Nov 19, 2012 · 14 revisions

The objects we store are being serialized to disk, because of this we need to take special care of object references as they will be lost after deserialization.

In the Getting started page we created a Comment object. We are using a forum as an example, so we are talking about a Comment on a Topic. Lets see how we can add references from one to the other:

public class Topic implements Persistent {
    public final static long serialVersionUID = -9038882251579382910L;

    private String title = "";
    private PersistentList<Long, Comment> comments;
    private Date lastPost;

    public void addComment(Comment comment) {
        getComments().add(comment);

        lastPost = new Date();
    }

    public PrevaylerList<Comment> getComments() {
        if (comments == null) {
            comments = new PersistentList<Long, Comment>(Comment.class);
        }

        return comments;
    }

    // skipped the rest
}

The PrevaylerList only holds the ids of the objects added, when iterating the list the actual objects are retrieved from the memory model. This way we can restore the references between objects when reapplying the transactions at startup.

We check if the comments field is null because of object (de)serialization. If we add a field to an existing model, all objects already serialized will be restored with this field being null. Adding an assignment in the constructor or declaration doesn't fix this(!).

Next: Transactions

Clone this wiki locally