Understanding mappedBy annotation in Hibernate

前端 未结 3 622
猫巷女王i
猫巷女王i 2020-12-08 16:25

I am trying to understand the mappedBy attribute of @OneToMany annotation in JPA. I created below example where a Customer has a list of Orders:

相关标签:
3条回答
  • 2020-12-08 17:15

    Is normal this behavior mappedBy indicates only that the entity in this side is the inverse of the relationship, and the owner resides in the "other" entity.

    I suggest you this link

    0 讨论(0)
  • 2020-12-08 17:17

    That's normal.

    With the mappedBy, you directly tell Hibernate/JPA that one table owns the relationship, and therefore it is stored as a column of that table.

    Without, the relationship is external and Hibernate/JPA need to create another table to store the relationship.

    Example:

    • A stackoverflow Question have several Answer.
    • An Answer is owned by one and only one Question.

    In plain JDBC, you would create two table:

    Questions(Question_ID, ...);
    Answers(Answer_ID, Question_ID, ...);
    

    Where Question_ID is foreign key referencing Question.Question_ID.

    As for the other case, I don't have a real case since there are almost every time many to many with a unique constraint (eg: a Question may have several Answer, and Answer may have physically have several Question, but appears only once for any Question).

    0 讨论(0)
  • 2020-12-08 17:17

    A OneToMany has two main ways it can be accomplished in the database.

    1. using a relation table (M:M)
    2. using a foreign key in the target table. (1:M)

    If you leave a OneToMany mapping and let it default, it will by default use a relation table, which is what you seem to want. If you don't want a join table to be used, you would either specify a JoinColumn which sets up a foreign key relationship much like a OneToOne, but in the opposite direction - it tells the provider what field in the target table points to this entity's primary key. But commonly the target foreign key is mapped in the target entity - it is a ManyToOne after all - and so the mappedby is used to specify that this OneToManyshould use the relationship already defined in the target entity.

    In this case, mappedBy=customer tells it to look at the customer property mapping within the Order entity. There, it finds customer has a ManyToMany mapping with a default joinColumn customer_id that it also uses for the OneToMany. Because it is already mapped within the Order entity, the OneToMany is read-only. This ensures that should the two relationships be out of sync, JPA has one side to always trust and use to set the database field.

    0 讨论(0)
提交回复
热议问题