Play module “associations” 1.0 released

Today I have released version 1.0 of the play [associations] module. I would like to elaborate a bit more on the rationale for this module.

Imagine the following simple model:

public class Forum {
    @OneToMany(cascade=CascadeType.ALL, mappedBy="forum")
    public List<Post> posts;
} 
public class Post {
    @ManyToOne
    public Forum forum;
}

Before the Module

In model management there are 3 phases, creation, manipulation and deletion. Under normal conditions (read play without associations module) these would be implemented like this:

1. Object creation and association creation

Forum forum = new Forum();
Post post = new Post();
forum.posts.add(post);
post.forum = forum; // don't forget this
forum.save(); // using CascadeType.ALL etc. this will cascade

2. Manipulation of existing objects

Post post = ...
post.forum.posts.remove(post); // don't forget this
Forum forum2 = new Forum();
forum2.posts.add(post);
post.forum = forum2; // don't forget this
forum2.posts.add(post);
forum.save(); // cascades
forum2.save(); // cascades

3. Deletion of objects

// this can be accomplished using
public class Forum {
  @OneToMany(cascade = CascadeType.ALL, orphaneRemoval = true)
  public List&lt;Post&gt; posts;
}
Post post = ...
post.forum.posts.remove(post);
post.forum = null; // don't forget this
forum.save();

With the Module

Now fast forward to an implementation *with* the associations module, this all gets much easier and intuitive to write:

1. Object creation and association creation

Forum forum = new Forum();
Post post = new Post();
forum.posts.add(post);
forum.save(); // using CascadeType.ALL etc. this will cascade

2. Manipulation of existing objects

Post post = ...
Forum forum2 = new Forum();
forum2.posts.add(post);
forum.save(); // cascades
forum2.save(); // cascades

3. Deletion of objects

Post post = ...
post.forum = null;
forum.save();

IMO this is much more intuitive. If you add a post to a forum, you’d expect that the previous forum does not reference it any more, wouldn’t you? Also, if you make a change on one side, you’d expect that the corresponding change on the other side is also made, wouldn’t you?

And this is exactly what this module provides, complete management of all JPA two-sided associations.

About these ads