What is JPA’s mappedBy for?

Asked

Viewed 9,897 times

4

Example:

@OneToMany(mappedBy = "chemical", fetch = FetchType.LAZY)
@LazyCollection(LazyCollectionOption.EXTRA)
@JsonIgnore
private List<SimulationChemicals> simulationChemicals;

Why is the use of mappedBy mandatory or important? I still don’t understand its function.

2 answers

7


The mappedBy is to indicate which is the inverse or non-dominant side of the relationship.

Other than Annotation @JoinColumn indicating that the entity is responsible for the relationship.

Ex:

public class Endereco {

    @Id
    @GeneratedValue
    private long id;

    private long numero;

    @OneToOne(mappedBy = "endereco") //Endereço não é o lado dominante
    private Pessoa pessoa;

    //getters e setters
}

5

There may be one-way or two-way relationships. When it is unidirectional only one class has the reference, which is the attribute, and this is noted.

@Entity
public class SystemUser {
  @OneToOne
  private Debt debt;
}

When Bidirectional the two classes have an attribute referencing each other.

@Entity
public class SystemUser {
  @OneToOne
  private Debt debt;
}

@Entity
public class Debt {
  @OneToOne
  @JoinColumn(mappedBy = "debt")
  private SystemUser systemUser;
}

Adds the mappedBy attribute on the non-dominant side. In class Systemuser has a Debt attribute, this is the name that will be used for mappedBy.

If the mappedBy attribute was not used, two relationships would be created between Systemuser and Debt. Each relationship with a dominant side.

Take Care of Bi-Directional Relationships. Look For More About Them.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.