hibernate OwningSide

hibernate OwningSide

https://www.baeldung.com/jpa-joincolumn-vs-mappedby


Defining the direction of the relationship between entities has no impact on the database mapping. It only defines the directions in which we use that relationship in our domain model.

unidirectional VS bi-directional

For a bidirectional relationship, we usually define:

  • the owning side
  • inverse or the referencing side

JoinColumn sepecify the column we use for join and entity association or element collections. On the other hand mappedby is used to define the refenrencing side (non-owning) side.

In a One-to-Many/Many-to-One relationship, the owning side is usually defined on the ‘*many'* side of the relationship.

Eg: An employee can have multiple email addresses. However, a given email address can belong exactly to a single employee.

Screen Shot 2020-11-25 at 5.30.40 PM

JoinColumn

@Entity
public class Email {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "employee_id")
private Employee employee;

// ...

}

It simply means that our Email entity will have a foreign key column named employee_id referring to the primary attribute id of our Employee entity.

Once we have defined the owning side of the relationship, Hibernate already has all the information it needs to map that relationship in our database

mappedBy

@Entity
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "employee")
private List<Email> emails;

// ...
}

the value of *mappedBy* is the name of the association-mapping attribute on the owning side.

Owning side

https://stackoverflow.com/questions/2749689/what-is-the-owning-side-in-an-orm-mapping