Last updated Dec 8, 2017

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

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

Label.java

1
2
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

1
2
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:

1
2
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.

Rate this page: