@OneToMany without inverse relationship and without a join table?

前端 未结 3 1839
天命终不由人
天命终不由人 2020-12-08 04:00

This is a similar problem to \"Hibernate @OneToMany without a separate join table\", in that I need a @OneToMany relationship without a join table. However, I would also li

3条回答
  •  一向
    一向 (楼主)
    2020-12-08 04:43

    The JPA 1.0 specification does NOT support unidirectional OneToMany mapping without a Join Table.

    And using a JoinColumn on a OneToMany isn't allowed in standard JPA 1.0 (only on a OneToOne, ManyToOne or ManyToMany). It is in JPA 2.0 though.

    From the JPA 1.0 specification:

    2.1.8.5.1 Unidirectional OneToMany Relationships

    The following mapping defaults apply:

    Entity A is mapped to a table named A. Entity B is mapped to a table named B. There is a join table that is named A_B (owner name first). This join table has two foreign key columns. One foreign key column refers to table A and has the same type as the primary key of table A. The name of this foreign key column is formed as the concatenation of the following: the name of entity A; "_"; the name of the primary key column in table A. The other foreign key column refers to table B and has the same type as the primary key of table B and there is a unique key constraint on it. The name of this foreign key column is formed as the concatenation of the following: the name of the relationship property or field of entity A; "_"; the name of the primary key column in table B.

    To sum up, if you don't want a Join Table (and full read/write support) and still want to be JPA compliant, make the association bidirectional (with an inverse side).

    The wiki book link below discusses a trick (mapping the target table as the join table) to "work around" the problem but this only works for reads, writes won't work.

    References

    • JPA 1.0 specification
      • 2.1.8.2 Bidirectional ManyToOne / OneToMany Relationships
      • 2.1.8.5.1 Unidirectional OneToMany Relationships
      • 9.1.6 JoinColumn Annotation (discusses in which context this annotation can be used)
    • JPA Wiki Book
      • 2.1 Undirectional OneToMany, No Inverse ManyToOne, No Join Table (JPA 2.0)

提交回复
热议问题