simpatico
simpatico

Reputation: 11107

How to represent a 3-way relation with JPA?

A user may have several labels, and links. Then, a user associates a label (or more) to a link. How does one represent the later relationship?

A solution could be a many-to-many relationship btw user and link with the optional attribute label. http://en.wikibooks.org/wiki/Java_Persistence/ManyToMany#Mapping_a_Join_Table_with_Additional_Columns In this case the relationship btw user and label may better be 'virtual'.

Any alternative I'm not seeing?

PS: I've used google bookmarks terminology, as it matches my case quite well.

Upvotes: 4

Views: 3264

Answers (3)

Pascal Thivent
Pascal Thivent

Reputation: 570505

If my understanding is correct, then you are in the following case:

Replacing ternary relationships

When ternary relationships occurs in an ER model they should always be removed before finishing the model. Sometimes the relationships can be replaced by a series of binary relationships that link pairs of the original ternary relationship.

                            alt text
(source: grussell.org)

                                                   Figure

: A ternary relationship example

  • This can result in the loss of some information - It is no longer clear which sales assistant sold a customer a particular product.
  • Try replacing the ternary relationship with an entity type and a set of binary relationships.

Relationships are usually verbs, so name the new entity type by the relationship verb rewritten as a noun.

  • The relationship sells can become the entity type sale.

                            alt text
(source: grussell.org)

                                                  Figure : Replacing a ternary relationship

  • So a sales assistant can be linked to a specific customer and both of them to the sale of a particular product.
  • This process also works for higher order relationships.

And this would be my suggestion: introduce a new entity.

Upvotes: 6

mdma
mdma

Reputation: 57757

Adding a nullable 'label' the user link will only allow one label for each link. If you only need one label, the go with that.

If you need multiple labels per link, then introduce a 3rd entity, e.g.

class LinkLabel
{
   @ManyToOne
   Link link;

   @ManyToOne
   Label label;  

   @ManyToOne
   User user;

}

Upvotes: 1

Bozho
Bozho

Reputation: 597234

Just have

class Label {
    ...
    @OneToOne
    private Link link;
}

and/or

class Link {
    ...
    @OneToOne
    private Label label;
}

Upvotes: 1

Related Questions