PostgreSQL inheritance with JPA, Hibernate

后端 未结 3 2090
一整个雨季
一整个雨季 2020-12-19 08:36

we have question about inheritance in PostgreSQL and mapping it as entities in JPA. Our database, and tables we want to map are:

CREATE TABLE Answer (
    id         


        
3条回答
  •  臣服心动
    2020-12-19 09:03

    Inheritance in Hibernate has nothing to do with PostgreSQL inheritance, even though both try to accomplish the same and might look the same.

    The reason for this is that Hibernate takes the SQL standards as base, and adjusts the small specific features from each RDBMS. For instance, while MySQL have an "auto-increment" for sequential IDs, Oracle uses sequences.

    Historically, data inheritance (or specialization) has been done by using separate tables for the specific fields, with primary-foreign-keys linking the tables together. In your example, MatchAnswer would have the ID as PK and FK to Answer.idAnswer. Same with TrueFalseAnswer (the ID is PK/FK to Answer.idAnswer).

    The "inherits" definition that you posted is not (AFAIK) defined in any SQL standard, so, I'd be surprised if Hibernate supported this, specially because it seems to be something extremely specific to PostgreSQL and it seems it's a somewhat experimental feature: look at "Caveats" on the "Inheritance" chapter of the PostgreSQL documentation.

    That said, I'd suggest to keep your data sane, mapping them according to the best relational-model practices. Then, in your Hibernate mappings, you can express data inheritance where it makes sense.

提交回复
热议问题