Skip to content

Relationships

Michele Scuttari edited this page Apr 2, 2018 · 1 revision

1:1

A one to one relationship can be realised using the @OneToOne annotation. The owning side of the relationship must also have a @JoinColumn, @JoinColumns or @JoinTable annotation specifying the columns involved in the link.

The non owning side can avoid to specify the relationship field if it is not needed. If present, its @OneToOne annotation must specify the name of the above mapping field through the usage of the mappedBy parameter.

@Entity
public class User {
    @OneToOne
    @JoinColumns({
            @JoinColumn(name = "address_city", referencedColumnName = "city"),
            @JoinColumn(name = "address_street", referencedColumnName = "street")
    })
    public Address address;
}

@Entity
public class Address {
    @Id
    @Column(name = "city")
    public String city;

    @Id
    @Column(name = "street")
    public String street;

    // Not mandatory
    @OneToOne(mappedBy = "address")
    public User user;
}

1:N

A one to many relationship can be realised using the @OneToMany and @ManyToOne annotations.

Similarly to the one to one relationship, the @ManyToOne annotation is for the owning side of the relationship, while the @OneToMany annotation is for the non owning one and thus can be omitted. As before, the owning side must specify the join columns or an eventual join table.

@Entity
public class Item {
    @Id
    @Column(name = "code")
    public int code;

    @JoinColumn(name = "order_id", referencedColumnName = "id")
    public Order order;
}

@Entity
public class Order {
    @Id
    @Column(name = "id")
    public int id;

    // Not mandatory
    @OneToMany(mappedBy = "order")
    public Collection<Item> items;
}

N:N

A many to many relationship can be realised using the @ManyToMany annotation.

Its usage is equal to the one to one case, except that a join table must be used for the owning side (join columns can't be used).

@Entity
public class Book {
    @Id
    @Column(name = "title")
    public String title;

    @Id
    @Column(name = "year")
    public int year;

    @ManyToMany
    @JoinTable(
            name = "authors",
            joinClass = Book.class,
            joinColumns = {
                    @JoinColumn(name = "book_title", referencedColumnName = "title"),
                    @JoinColumn(name = "book_year", referencedColumnName = "year")
            },
            inverseJoinClass = Person.class,
            inverseJoinColumns = {
                    @JoinColumn(name = "author_ssn", referencedColumnName = "ssn")
            }
            )
    public Collection<Person> authors;
}

@Entity
public class Person {
    @Id
    @Column(name = "ssn")
    public String ssn;

    // Not mandatory
    @ManyToMany(mappedBy = "authors")
    public Collection<Book> books;
}
Clone this wiki locally