I have started reading JPA from EJB3 in Action by (Debu Panda, Reza Rahman, Derek Lane). In that book, for @OneToMany and @ManyToOne (also in @OneToOne) under bidirectional relationship,an explanation on "MappedBy" was given.
From the example mentioned in the book,
where there is a bidirectional one to one relationship between User and BillingInfo.
From the above example, based on the explanation given,
The first is the mappedBy="billingInfo" specification C. This
tells the container that the “owning” side of the relationship exists in the User
class’s billingInfo instance variable. The concept of a relationship owner doesn’t
originate from domain modeling. It exists as a convenience to define the database
mapping for a relationship only once instead of repeating the same mapping for
both directions of a relationship.
To be honest with you, I did not understand this clearly. Could some one help me digest this ?
One more irrelevant question, If we learn JPA, would it be easy to understand Hibernate ORM with out much learning curve ?
The domain modelling here is a bidirectional one-to-one relationship:
User <----> BillingInfo
Means the application requires both these queries:
- Get the BillingInfo for this User
- Get the User for this BillingInfo
So how do you map this to a DB schema?
One simple method is have foreign key to the other table from both tables:
But do we ever do this? It's a waste of storage to use 2 FKs when only one is sufficient.
Instead, the normal way is to have one foreign key. The "owning side" means the table which has the foreign key column.
So how do you tell the ORM framework that the bidirectional relationship is represented by only one foreign key?
Answer: use the "mappedBy" annotation element. It tells the target entity in the relatioship who owns the relationship.
In its absence, ORM would expect to find UserID foreign key field in the BillingInfo table, and fail on not finding it.
In its presence, ORM knows that to get the User object for a BillingInfo, it should use the BillingInfo ID foreign key in User table, without an additional foreign key column in BillingInfo table.
For your other question, JPA concepts are very much derived from Hibernate and other ORM frameworks. Chronologically, the frameworks came first and then JPA was designed as a standard based on them. The important concepts and terminology are same. It's ok to learn the standard first - you'll understand hibernate and other ORM frameworks easily if you know JPA. All frameworks provide both their proprietary API (including annotations and XML descriptors) as well as the JPA API. JPA sets a bar, but most frameworks provide additional functionality over it through their proprietary APIs. Code the app as much as possible to JPA APIs, and if you really need some advanced Hibernate functionality, then isolate the code that requires that functionality and make only those classes depend on the proprietary Hibernate API.