问题
I'm working on a JPA Compliancy kit for my internship... Part of that kit involves testing correct implementation of corner cases.
@ManyToMany
has a mappedBy attribute. JPA states that:
String mappedBy - The field or property that owns the relationship. Required unless the relationship is unidirectional.
No default is given - the default column is empty.
Given a bidirectional @ManyToMany
- this example is from the JPA 2.0 JSR-317 specification itself!
Customer
@ManyToMany
@JoinTable(name="CUST_PHONES")
public Set<PhoneNumber> getPhones() { return phones; }
PhoneNumber
@ManyToMany(mappedBy="phones")
public Set<Customer> getCustomers() { return customers; }
The mappedBy attribute hasn't been defined in the @ManyToMany
of Customer
! Is there a default for bidirectional mappings that I'm not aware of, or what?
I looked at similar cases and found:
@OneToOne
- mappedBy is optional, no default
@OneToMany
- exactly the same as @ManyToMany
(mappedBy is optional for bidirectional, with no default)
In short, my question:
For @ManyToMany
and @OneToMany
, what should be placed in the mappedBy attribute for the owning side of the relationship (Customer
in example)?
回答1:
This is far from being a corner case. Every bidirectional association has an owner side and an inverse side.
JPA uses the owning side to decide if an association exists between two entities. The other side is ignored.
The owning side is the one which defines how the association is mapped (using the JoinColumn, JoinTable, etc. annotations). It doesn't have any mappedBy
attribute.
The inverse side uses the mappedBy
attribute to say: "Hey, I'm just the inverse association of the one mapped by the following property".
So, by definition, the owning side doesn't have a mappedBy
attribute. If it had one, it wouldn't be the owning side.
This is well explained in the JPA spec. If you need to build a compliancy kit for this specification, you'd better read and understand it.
I don't really see the point of writing such a compliancy kit since, as written on the JPA2 JSR home page,
As required by the Java Specification Participation Agreement (JSPA), the Java Persistence API, version 2.0 TCK will be licensed at no charge without support to qualified not-for-profit entities. Such qualification will be verified by the Compatibility Testing Scholarship Program. Support may also be provided at no charge with approval of the scholarship board. For more information, please refer to: http://java.sun.com/scholarship/.
来源:https://stackoverflow.com/questions/9278015/manytomany-onetomany-mappedby-attribute-for-bidirectional-association