What is JPA's mappedBy for?

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 did not understand his function yet.

    
asked by anonymous 08.01.2016 / 18:23

2 answers

5

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

Other than annotation @JoinColumn which indicates 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
}
    
08.01.2016 / 19:41
1

There may be a Unidirectional or Bidirectional relationship. 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 it is 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 the SystemUser class has a debt attribute, this is the name that will be used for mappedBy.

If you did not use the mappedBy attribute, you would create two relationships between SystemUser and Debt. Each relationship with a dominant side.

Watch out for two-way relationships. Look for more about them.

    
08.02.2016 / 02:36