Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

 these examples on TopLink JPA Annotation Reference:

Example 1-59 @OneToMany - Customer Class With Generics

@Entity

public class Customer implements Serializable {

    ...

    @OneToMany(cascade=ALL, mappedBy="customer")

    public Set<Order> getOrders() { 

        return orders; 

    }

    ...

}

Example 1-60 @ManyToOne - Order Class With Generics

@Entity

public class Order implements Serializable {

    ...

    @ManyToOne

    @JoinColumn(name="CUST_ID", nullable=false)

    public Customer getCustomer() { 

        return customer; 

    }

    ...

}

It seems to me that the Customer entity is the owner of the association. However, in the explanation for the mappedBy attribute in the same document, it is written that:

if the relationship is bidirectional, then set the mappedBy element on the inverse (non-owning) side of the association to the name of the field or property that owns the relationship as Example 1-60 shows.

However, if I am not wrong, it looks like in the example, the mappedBy is actually specified on the owning side of the association, rather than the non-owning side.

So my question is basically:

  1. In a bidirectional (one-to-many/many-to-one) association, which of the entities is the owner? How can we designate the One side as the owner? How can we designate the Many side as the owner?
  2. What is meant by "the inverse side of the association"? How can we designate the One side as the inverse? How can we designate the Many side as the inverse?

1 Answer

0 votes
by (46k points)

Simple rules of bidirectional relationships:

1.For many-to-one bidirectional relationships, the many side is always the owning side of the relationship. Example: 1 Room has many Person (a Person belongs one Room only) -> owning side is Person

2.For one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key.

3.For many-to-many bidirectional relationships, either side may be the owning side.

Hope can help you.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...