ManyToMany Relationship

In ActiveObjects many to many relationships are defined thanks to the net.java.ao.ManyToMany annotation. It also requires another entity that links both sides of the many to many relationship.

Let's have a look at an example of such relation ship in the DogFood blog. The relationship is defined between posts (of type Post) and labels (of type Label).

Post.java
public interface Post extends Entity
{
    ...
    @ManyToMany(value = PostToLabel.class)
    public Label[] getLabels();
    ...
}

Label.java
public interface Label extends Entity
{
    ...
    @ManyToMany(value = PostToLabel.class)
    public Post[] getPosts();
}

Note how posts and labels both reference each other, but no setter exists. Also the @ManyToMany annotation defines a third Entity of type PostToLabel:

PostToLabel
public interface PostToLabel extends Entity
{
    public void setPost(Post post);
    public Post getPost();

    public void setLabel(Label label);
    public Label getLabel();
}

There is no annotation here. However this class clearly defines a relationship between a Post and a Label.

Actually associating a post to a label and persisting this association is as simple as:

private void associatePostToLabel(Post post, Label label) throws SQLException
{
    final PostToLabel postToLabel = entityManager.create(PostToLabel.class);
    postToLabel.setPost(post);
    postToLabel.setLabel(label);
    postToLabel.save();
}

You can see this code in the BlogService of the DogFood blog.

New attributes on entity annotations in Active Objects 0.22.1

The OneToOne, OneToMany and ManyToMany annotations are used to define relationships in Active Objects. If you have used one of these to annotate a method as one end of a relationship, you can now set an attribute(s) that specifies the method on the remote end of the relationship. In versions prior to 0.22.1, Active Objects would attempt to infer the method by the type, which did not work in all situations.

  • ManyToMany annotation: New "reverse" and "through" attributes. Set the "reverse" attribute to the name of the corresponding getter on the intermediate interface. Set the "through" attribute to the name of the getter on the intermediate interface that refers to the remote interface.

If you do not set these attributes, Active Objects will revert to inferring the method by type. However, in a future upgrade, specifying these attributes will be required.

Note, the Active Objects plugin was upgraded to 0.22.1 in JIRA 6.1.

Was this page helpful?

Have a question about this article?

See questions about this article

Powered by Confluence and Scroll Viewport