taboubim taboubim - 4 months ago 11
Java Question

mappedBy refers to the Class Name or to the Table Name?

When we use the mappedBy annotation in @OneToMany for example, did we mention the Class Name or the Table Name ?

An exemple :

@Entity
@Table(name = "customer_tab")
public class Customer {
@Id @GeneratedValue public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
private Integer id;

@OneToMany(mappedBy="customer_tab")
@OrderColumn(name="orders_index")
public List<Order> getOrders() { return orders; }

}


So which of these two is correct ? :


  • @OneToMany(mappedBy="customer_tab")

  • @OneToMany(mappedBy="Customer") ?



Thank you!

Answer

Neither is correct. From the documentation:

mappedBy
public abstract java.lang.String mappedBy
The field that owns the relationship. Required unless the relationship is unidirectional.

The mappedBy annotation indicates that the field which it labels is owned by the other side of the relationship, in your example the other side of a one-to-many relationship. I don't know exactly what your schema is, but the following class definitions would make sense:

@Entity
@Table(name = "customer_tab")
public class Customer {
    @OneToMany(mappedBy="customer")
    @OrderColumn(name="orders_index")
    public List<Order> getOrders() { return orders; }

}

@Entity
public class Customer {
    @ManyToOne
    @JoinColumn(name = "customerId")
    // the name of this field should match the name specified
    // in your mappedBy annotation in the Customer class
    private Customer customer;
}