Reputation: 643
documentation says:
The many side of many-to-one bidirectional relationships must not define the mappedBy element. The many side is always the owning side of the relationship.
Can you explain why? what the reason?
Upvotes: 3
Views: 815
Reputation: 1
This makes sense.
Assume you have two entities: Post, which represents the "one" side, and Comments, which represents the "many" side of the relationship. Consider that the JPA allows us to specify the mappedBy attribute in the @ManyToOne annotation. Thus, it means Post will be the owning side and Comment will be the inverse side and in the database, the table post will have a foreign key referring to the primary key of the table comments. In this scenario, the issue is that one instance of the entity Post has to store multiple instances of the entity Comments, and an ORM framework will fail to reflect this relationship in the relational database because one record cannot contain multiple foreign key values(practically).
That's why the "one" side in a one to many bi-directional relationship can't be the owning side.
Upvotes: 0
Reputation: 742
Each of the (potentially many) rows representing the entity on the "many" side contain (foreign key) references back to single row representing the entity on the "one" side of the relationship as a single database column. In order for the "one" side to own the relationship, the keys for all of the rows corresponding to the "many" side would have to fit into a single database table row, which isn't practical.
In other words, if A
is the "many" side and B
is the "one side", for each row in the B
table, there are potentially several rows in table A
that contain a reference to it. Each of those B rows can store the key of the linked A row in a single column. There's no way for that one A row to store the keys of all those B rows.
For the same reason, in the case of a many-to-many relationship, a join table always ends up getting used in addition to the tables representing the entities in order to link the foreign key references as single columns.
Upvotes: 4
Reputation: 616
thats because in the database, the many side has the foreign key. for example consider tables User and Transaction with relation user has many transactions. In the transaction table, every transaction has a user_id which is a foreign key to the user table not the other way round. User table does not have a transaction_id.
Upvotes: 2