Database: 1:N = Inverse (N:1) ?
In database, we can map "One to Many" and "Many to one" relationship between tables by creating Foreign key (FK) column for table on the "Many" side of the relationship.
Say for example, we want to map "One to Many" (1:N) relationship between Customer and Order. "One customer can have multiple Orders. But one Order can have only one Customer associated"
Which table is on the "Many" side of the relationship? - Order table. So we can create Foreign Key(FK) in Order table pointing to Primary key(PK) in Customer table.
You have created both 1:N (From Customer to Order) and N:1 ( From Order to Customer) mapping in your database!!!
Query - "Give me all the order names for the given customer name"?
- Select order_name from Order,Customer where customer_name="jay";
The above query is nothing but just a INNER JOIN. Is there any better way to write same query?--(Have you heard of Lazy Loading?)
OR Mappers : 1:N = Inverse (N:1) ?
Order class: (JPA Annotations used)
@ManyToOne
@JoinColumn(name="customer_id") //customer_id is a FK field in Order table.
public Customer getCustomer();
public void setCustomer(Customer customer);
You have mapped "Many to One" relationship, but not "One to Many" yet.
you have two options to get the data using Order.getCustomer() :: Lazy Loading(On demand) or JOIN(Eager Loading/Pre-Loading/Pre-Fetching)
Customer class: (JPA Annotations used)
@OneToMany(mappedBy = "customer_id") //customer_id is a FK field in Order table.
List
void setOrders(List
Now you have mapped "One to Many" relationship. You are ready to traverse in both way now from Customer -> Order and Order -> Customer in your code.
Under the cover, OR mapppers use Primary/Foreign key mechanism to map 1:N and N:1 relationship..but please do not change your annotation blindly in your POJO "@ManyToOne" != "@OneToMany"
Little bit more hammering:>>>>>> If you want to map many-to-many relationship in between two database tables, you will need one Associate table or JOIN table. This JOIN table will have two foreign keys pointing to the primary key of the two entity tables. So you will have Many-to-One mapping from JOIN table to each entity table.
1 comment:
Interesting to know.
Post a Comment