Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 786
Mohamed Taboubi Avatar asked Jul 19 '16 00:07

Mohamed Taboubi


Video Answer


1 Answers

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 Order {
    @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;
}
like image 159
Tim Biegeleisen Avatar answered Oct 09 '22 19:10

Tim Biegeleisen